#**************************************************************************
#   Copyright (C) 2009 by Michael Andreen <harvATruinDOTnu>               *
#                                                                         *
#   This program is free software; you can redistribute it and/or modify  *
#   it under the terms of the GNU General Public License as published by  *
#   the Free Software Foundation; either version 2 of the License, or     *
#   (at your option) any later version.                                   *
#                                                                         *
#   This program is distributed in the hope that it will be useful,       *
#   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#   GNU General Public License for more details.                          *
#                                                                         *
#   You should have received a copy of the GNU General Public License     *
#   along with this program; if not, write to the                         *
#   Free Software Foundation, Inc.,                                       *
#   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
#**************************************************************************/
package NDIRC::Delling;

use strict;
use warnings;
use feature ':5.10';

use Moose;
extends 'NDIRC::Bot';

use POE::Session;
use ND::DB;

use NDIRC::DiscordContext;

my ($tick,$stattick) = (0,0);
my $last_announcement = 0;

after irc_public => sub {
	my ($self,$sender, $who, $where, $msg) = @_[OBJECT,SENDER, ARG0 .. ARG2];
	my ($nick,$username,$address) = ( split /[!@]/, $who );
	my $channel = $where->[0];

	my $irc = $sender->get_heap();

	#$irc->yield(privmsg => $channel, "Authed? " . $irc->is_nick_authed($nick));
	my $dbh = DB();
	my $seen = $dbh->prepare_cached(q{UPDATE users SET laston = NOW() WHERE hostmask = ?});
	$seen->execute($address);

	my $nickname = $irc->nick_name;
	if ($msg =~ /^(\S+): (.+)$/ && $self->disp->has_command('anon',$channel)){
		local $_ = $1;
		my $text = $2;
		unless ($irc->is_channel_member($channel,$1) || /(Constructing|Researching)/){
			$msg = ".anon $_ $text";
			$self->parseCommand($msg,$irc,$nick,$address,$channel,$dbh);
		}
	}elsif ($self->parseCommand($msg,$irc,$nick,$address,$channel,$dbh)){
		#Command parsed and run successfully
	}
};

after irc_msg => sub {
	my ($self,$sender, $who, $where, $msg) = @_[OBJECT,SENDER, ARG0 .. ARG2];
	my ($nick,$username,$address) = ( split /[!@]/, $who );
	my $irc = $sender->get_heap();

	my $dbh = DB();
	my $seen = $dbh->prepare_cached(q{UPDATE users SET laston = NOW() WHERE hostmask = ?});
	$seen->execute($address);

	if ($self->parseCommand($msg,$irc,$nick,$address,'pm',$dbh)){
		#Command parsed and run successfully
	}else{
		$irc->yield(notice => $nick, "unknown command");
	}
};

sub irc_join {
	my ($self,$sender, $who, $channel) = @_[OBJECT,SENDER, ARG0 .. ARG1];
	my ($nick,$username,$address) = ( split /[!@]/, $who );
	my $irc = $sender->get_heap();
	my $disp = $self->disp;

	my $dbh = DB();
	my $seen = $dbh->prepare_cached(q{UPDATE users SET laston = NOW() WHERE hostmask = ?});
	$seen->execute($address);

	if($self->disp->has_command('voice',$channel)){
		my $flags = $dbh->prepare_cached(q{
SELECT DISTINCT flag
FROM users u
	JOIN groupmembers g USING (uid)
	JOIN channel_group_flags gf USING (gid)
WHERE u.hostmask = $1 AND channel = $2 AND flag IN ('o','v');
		});
		$flags->execute($address, $channel);
		my $mode = '';
		my @who;
		while (my ($flag) = $flags->fetchrow()){
			$mode .= $flag;
			push @who, $nick;
		}
		say "$mode - @who";
		$irc->yield(mode => $channel, $mode, @who) if $mode;
	}

	if (lc $channel ~~ @{$self->targets->{members}}){
		if (time - $last_announcement < 1){
			$last_announcement = time;
			return;
		}
		my $user = $dbh->selectrow_hashref(q{
SELECT uid,pid,hostmask,password
	,(SELECT max(time) FROM forum_thread_visits WHERE uid = u.uid) AS last_forum_visit
FROM users u WHERE hostmask = ?
		}, undef, $address);
		if ($user){
			unless ($user->{password}) {
				$irc->yield(privmsg => $channel, "$nick: Get a new random password with /msg delling !getpass . If you don't know your username, then you can get it with .points");
			}
			if ($tick > 12 && not defined $user->{pid}){
				$irc->yield(privmsg => $channel, "$nick: go to https://nd.ruin.nu/ and enter your coords.");
			}

			if (not defined $user->{last_forum_visit}){
				$irc->yield(privmsg => $channel, "$nick: Go read the forum! https://nd.ruin.nu/forum");
			}else {
				my $unread = $dbh->selectrow_hashref(q{SELECT * FROM unread_posts($1)},undef,$user->{uid});
				if ($unread && $unread->{new}){
					$irc->yield(notice => $nick, "$unread->{new} posts since your last forum visit ($unread->{unread} unread posts in total) https://nd.ruin.nu/forum/allUnread");
				}
			}
		}
		if (time - $last_announcement < 2){
			$last_announcement = time;
			return;
		}
		$last_announcement = time;
	}
}

sub refresh {
	my ($self,$kernel,$heap) = @_[OBJECT,KERNEL,HEAP];
	$kernel->delay( refresh => 60 );
	print 'Time: ' . time() . ' Lag: ' . $heap->{connector}->lag() . "\n";

	my $irc = $heap->{irc};
	my $disp = $self->disp;
	my $dbh = DB();
	my $scans = $dbh->prepare(q{SELECT s.scan_id
			,coords(x,y,z),type
			,array_agg(sr.nick) AS nick
			,array_agg(sr.id) AS id
		FROM scan_requests sr
			JOIN scans s USING (pid,type)
			JOIN current_planet_stats USING (pid)
		WHERE sr.time > NOW() - '30 min'::INTERVAL
			AND s.tick >= sr.tick AND NOT sr.sent
		GROUP BY scan_id,x,y,z,type
		});
	my $sentscan = $dbh->prepare(q{UPDATE scan_requests
		SET sent = TRUE WHERE id = ANY($1)
		});
	$scans->execute;
	while (my $scan = $scans->fetchrow_hashref){
		$self->message("($scan->{coords} $scan->{type})"
			." http://game.planetarion.com/showscan.pl?scan_id=$scan->{scan_id}"
			, @{$scan->{nick}});
		$sentscan->execute($scan->{id});
	}

	my @row = $dbh->selectrow_array(q{SELECT tick(), max(tick) FROM planet_stats});
	if ($tick != $row[0]){
		$tick = $row[0];
		$self->toTarget(def => "New tick: $tick");
	}
	if (defined $row[1] && $stattick != $row[1]){
		$stattick = $row[1];
		$self->toTarget(spam => "New tick: $stattick");
	}
	my $ircreqs = $dbh->prepare(q{SELECT id,username,message,channel FROM irc_requests NATURAL JOIN users WHERE not sent});
	my $upircreq = $dbh->prepare(q{UPDATE irc_requests SET sent = TRUE WHERE id = ?});
	$ircreqs->execute;
	while (my $req = $ircreqs->fetchrow_hashref){
		if ($req->{channel} eq 'def'){
			$self->toTarget(def => "<c04>## $req->{username} via webbie ## >></c> $req->{message}");
			$self->parseCommand("~report_incs $req->{message}",$irc,$req->{username},' BATCH ','#def-ndawn',$dbh);
		}else{
			$self->toTarget($req->{channel} => "<$req->{username} via webbie> $req->{message}");
		}
		$upircreq->execute($req->{id});
	}
	my $defmissions = $dbh->prepare(q{
SELECT username,call,tick,dm.fleet,p.value
	,100 * SUM(fs.amount * (metal + crystal + eonium) / 100) / p.value AS value
FROM users u
	JOIN current_planet_stats p USING (pid)
	JOIN launch_confirmations USING (uid)
	JOIN fleets f USING (fid)
	JOIN fleet_ships fs USING (fid)
	JOIN defense_missions dm ON f.fid = dm.fleet
	JOIN ship_stats ss USING (ship)
WHERE NOT dm.announced
GROUP BY username,call,tick,dm.fleet,p.value
		});
	my $updefmis = $dbh->prepare(q{UPDATE defense_missions SET announced = TRUE WHERE fleet = ?});
	$defmissions->execute();
	while (my $mission = $defmissions->fetchrow_hashref){
		$self->toTarget(def => "<c06>$mission->{username} sent def</c> to call $mission->{call}, $mission->{value}% of value (tick $mission->{tick}) https://nd.ruin.nu/calls/edit/$mission->{call}");
		$updefmis->execute($mission->{fleet});
	}

}

after sig_usr2 => sub {
	my $self = shift;
};

after _start => sub {
 ($tick,$stattick) = DB()->selectrow_array(q{SELECT tick(),max(tick) FROM planet_stats});
};

after discord_message_create => sub {
	my ($self, $gw, $hash) = @_;

	my $author = $hash->{author};
	my $msg = $hash->{content};
	my $channel_id = $hash->{channel_id};
	my $author_name = $author->{username}.'#'.$author->{discriminator};
	my $author_id = $author->{id};
	return if $author->{'id'} eq $self->discord_id; # Ignore my own messages

	my $channel = "D-".$channel_id;
	if (exists $self->discord_channels->{$channel_id}) {
		$channel = 'dm' if ($self->discord_channels->{$channel_id}->{type} == 1);
	}

	say localtime(time) . " - $channel_id $channel $author_name $author_id";

	my $c = NDIRC::DiscordContext->new({
			discord_id => $author_name,
			channel_id => $channel_id,
			author_id => $author_id,
			channel => $channel,
			disp => $self->disp,
			model => DB(),
			bot => $self,
			discord => $self->discord,
		});

	return $self->handleCommand($c,$msg);

};

1;
