#**************************************************************************
#   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::Commands::Def;

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

use Moose;
use MooseX::MethodAttributes;

sub anon
	: Help(syntax: .anon nick message)
	: Type(def)
	: ACL(irc_anondef)
{
	my ($self,$c,$msg) = @_;

	my ($target,$mess) = $msg =~ /^(\S+) (.*)$/ or die 'ARGS';

	$c->message("msg $target", "<b>$mess</b>");
	$c->message("msg ".$c->channel, "<c03>$target << $mess</c>");
}

sub defcall
	: Help(syntax: .defcall [callid] | if a call id is given, then shiptypes and eta will be fetched from the database and added to the message)
	: Type(def)
	: ACL(irc_defcall)
{
	my ($self,$c,$msg) = @_;
	my ($callnr,$mess) = $msg =~ /^(\d+)?(.*)$/ or die 'ARGS';
	my $dbh = $c->model;

	my $callinfo = "";
	if ($callnr){
		my $st = $dbh->prepare(q{
SELECT covered
	,c.landing_tick - (SELECT value::integer FROM misc WHERE id = 'TICK') AS eta
	,concat(i.shiptype||'/') AS shiptype
FROM calls c
	JOIN incomings i ON i.call = c.id
	LEFT OUTER JOIN users dc ON dc.uid = c.dc
	JOIN users u ON u.uid = c.member
WHERE c.id = ?
GROUP BY c.id,c.landing_tick,c.covered
ORDER BY c.landing_tick;
		});
		my $call = $dbh->selectrow_hashref($st,undef,$callnr);
		unless (defined $call->{covered}){
			$c->reply("No call with id: $callnr");
			return;
		}
		chop($call->{shiptype});
		$callinfo = "(Anti $call->{shiptype} ETA: $call->{eta})";
		if($call->{covered}){
			$c->reply("Call <b>$callnr</b> $callinfo is covered.");
			return;
		}
	}
	$c->message("notice $ND::memchan", "DEFENSE REQUIRED!! WAKE UP!!");
	$c->message("msg $ND::memchan", "DEFENSE REQUIRED $mess $callinfo MSG "
		.$c->nick." TO RESPOND");
}

1;

