#/usr/bin/env perl

use strict;
use warnings;
use diagnostics;
use JSON;
use Module::Reload;
use threads;
use feature "say";
use Cwd 'abs_path';
use File::Basename;
use ENV::Util;

BEGIN {
    ENV::Util::load_dotenv('.env');
    
    my $script_dir = dirname(abs_path($0));
    push @INC, "$script_dir/src/lib";
}

use CsBot3::Matrix;

# my $jsonconf = "";
# open(my $config, "<", "config.json");
# foreach (<$config>)
# {
#     $jsonconf .= $_;
# }
# close $config;
# $config = decode_json $jsonconf;
# if ($@) {
#     die("Error parsing JSON: $@");
# }
# 
# my $modules = $config -> {"modules"};
# 
# foreach (@$modules)
# {
#     my $fullname = "csbot2::$_";
#     eval "use modules::$_";
#     die("Cannot load $_ : $@") if $@;
#     #say $_;
#     $fullname -> init();
# }
# 
# $|++; # enable autoflushing
# 
# my $irc;
# my $server = $config -> {"config"} -> {"server"};
# my $port = $config -> {"config"} -> {"port"};
# my $nick = $config -> {"config"} -> {"nick"};
# my $channels = $config -> {"config"} -> {"channels"};
# my $password = $config -> {"config"} -> {"password"};
# my $masters = $config -> {"config"} -> {"masters"};
# my $ignore = $config -> {"config"} -> {"ignore"};
# my $version = "0.2.6 now with slightly better module loading!";
my $matrix = CsBot3::Matrix::new($ENV{MATRIX_SERVER});

my %credentials = (
    type => "m.login.password",
    user  => $ENV{MATRIX_USER},
    password => $ENV{MATRIX_PASSWORD},
);

my $room = $ENV{MATRIX_DEFAULT_ROOM};

my $login = CsBot3::Matrix::login(\%credentials);

if($login) {
    CsBot3::Matrix::join_room($room);
    CsBot3::Matrix::subscribe("m.room.message", \&CsBot3::Matrix::send_message);
    CsBot3::Matrix->read_events();
}