package Logs;

use POE::Component::IRC::Plugin qw( :ALL );

use lib 'plugins';
use helpers;

use POSIX qw(strftime);

my $started = 0;
my $prof = "";
my $filename = "";

my $base_path = "/home/gauvain/public_html/";
my $url = "http://gauvain.pocentek.net/";

sub new {
    my $package = shift;
    return bless {}, $package;
}

sub PCI_register {
    my ( $self, $irc ) = splice @_, 0, 2;
    $irc->plugin_register( $self, "SERVER", qw(public) );
    return 1;
}

sub PCI_unregister {
    return 1;
}

sub S_public {
    my ( $self, $irc ) = splice @_, 0, 2;
    my $who = ${ $_[0] };
    my $nick = ( split /!/, ${ $_[0] } )[0];
    my $mask = (split /@/, ${ $_[0] } )[1];
    my $channel = ${ $_[1] }->[0];
    my $msg = ${ $_[2] };

    @tmp = (split / /, $msg);
    if (@tmp[0] ne "!log") {
        if ($started) {
            if ($nick eq $prof) {
                $show_nick = "<b>[ $nick]</b>";
            } else {
                $show_nick = "[ $nick]";
            }
            print LOGFILE "$show_nick $msg<br />\n";
            return PCI_EAT_PLUGIN;
        } else {
            return PCI_EAT_NONE;
        }
    }

    my $cmd = @tmp[1];
    my $name = @tmp[2];
    $prof = @tmp[3];

    if (($cmd eq "start") and (helpers::is_admin($who))) {
        if (not $prof) {
            $irc->yield( privmsg => $channel => "$nick: !log start session prof" );
            return PCI_EAT_PLUGIN;
        }
        if ($started) {
            $irc->yield( privmsg => $channel => "$nick: Je logue déjà une session" );
        }
        my $now = strftime ("%Y-%m-%d", localtime());
        $filename = "$now-$name.log.html";
        $started = 1;
        open LOGFILE, "> $base_path/$filename";
        print LOGFILE "<html>\n<body>\n";
        $irc->yield( privmsg => $channel => "$nick: -*- log dans $url$filename (prof: $prof) -*-");
        LOGFILE->autoflush(1);

        return PCI_EAT_PLUGIN;
    }
    if ($cmd eq "stop") {
        if (helpers::is_admin($who) or ($nick eq $prof)) {
            $started = 0;
            print LOGFILE "</body>\n</html>";
            close LOGFILE;
            $irc->yield( privmsg => $channel => "$nick: -*- fin du log dans $url$filename -*-");

            return PCI_EAT_PLUGIN;
        }
    }

    return PCI_EAT_NONE;
}

1;
