#**************************************************************************
#   Copyright (C) 2008 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::Scans;

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

use Moose;
use MooseX::MethodAttributes;

sub getscans
	: Help(syntax: .getscans X:Y:Z)
	: Type(pm)
{
	my ($self,$c,$args) = @_;
	my ($x,$y,$z) = $args =~ /(\d+)\D+(\d+)\D+(\d+)/ or die 'ARGS';
	$c->reply("https://nd.ruin.nu/stats/find/$x:$y:$z");
}

my %scanid = (p => 1, l => 2, d => 3, u => 4, n => 5, j => 7, a => 8);

my @scantypes = ('Planet','Landing', 'Development'
	,'Unit', 'News', 'Incoming', 'Jumpgate', 'Advanced Unit');

sub gs
	: Help(syntax: gs type X:Y:Z message | type is the first character in the scan name, like p for planet scan, message is a message to scanners, like plz or thanks like plz or thanks)
	: ACL(irc_gs)
	: Type(pm)
{
	my ($self,$c,$args) = @_;

	my ($typeid, $x, $y, $z, $msg) = $args =~ /^([pdunja]) (\d+)\D+(\d+)\D+(\d+) (\S.*)/
		or die 'ARGS';
	$typeid = $scanid{$typeid};
	my $type = $scantypes[$typeid-1];

	my $planet = $c->model->selectrow_array(q{SELECT planetid($1,$2,$3,tick())}
		,undef,$x,$y,$z);

	my $query = $c->model->prepare(q{SELECT scan_id
		FROM scans
		WHERE planet = $1 AND type = $2 AND tick >= tick()});
	$query->execute($planet,$type);

	if (my $scan = $query->fetchrow_hashref){
		$c->reply("scan already exist: "
			. "http://game.planetarion.com/showscan.pl?scan_id=$scan->{scan_id}");
	}else{
		my $req = $c->model->prepare(q{
SELECT * FROM scan_requests
WHERE uid = (SELECT uid FROM users WHERE hostmask ILIKE $1)
	AND planet = $2 AND type = $3 AND NOT sent
		});
		$req->execute($c->host,$planet,$type);

		my $id;
		if(my $scan = $req->fetchrow_hashref){
			$req = $c->model->prepare(q{
UPDATE scan_requests SET nick = $1, tick = tick(), time = NOW()
WHERE id = $2
			});
			$req->execute($c->nick,$scan->{id});
			$id = $scan->{id};
		}else{
			$req = $c->model->prepare(q{
INSERT INTO scan_requests (uid,nick,planet,type)
VALUES((SELECT uid FROM users WHERE hostmask ILIKE $1),$2,$3,$4) RETURNING (id)
			});
			$req->execute($c->host,$c->nick,$planet,$type);
			$id = $req->fetchrow;
		}

		if ($id){
			$c->message("msg $ND::scanchan"
				,"<b>$id</b> http://game.planetarion.com/waves.pl?id=$typeid&x=$x&y=$y&z=$z"
				. " ($x:$y:$z $type) | <".$c->nick."> $msg"
			);
			$c->reply("sent request ($x:$y:$z $type)");
		}else{
			$c->reply("something went wrong..");
		}
	}
}

my %scantypes;
{
	my $i = 1;
	%scantypes = map {$_ => $i++} @scantypes;
}

sub scanreqs
	: Help(syntax: .scanreqs [-pdunja] | Lists scan requests that haven't been handled. The argument can be used to omit types you don't have, like .scanreqs -ja to list all requests except jumpgates and advanced unit scans.)
	: ACL(irc_scanreqs)
{
	my ($self, $c, $msg) = @_;

	my @notype;
	if ($msg =~ /^-([pdunja]+)$/){
		for (split //, $1){
			push @notype, $scantypes[$scanid{$_}-1];
		}
	}elsif($msg){
		die 'ARGS';
	}

	my $reqs = $c->model->prepare(q{
SELECT min(sr.id) AS id, x,y,z,type
FROM scan_requests sr
	JOIN current_planet_stats p ON p.id = sr.planet
WHERE sr.time > NOW() - '30 min'::INTERVAL
	AND NOT EXISTS (SELECT scan_id FROM scans
		WHERE planet = sr.planet
			AND type = sr.type
			AND tick >= sr.tick
	)
	AND type <> ALL($1)
GROUP BY x,y,z,type
ORDER BY id
		});
	$reqs->execute(\@notype);
	my $text = '';
	while (my $req = $reqs->fetchrow_hashref){
		$text .= "<b>$req->{id}</b> http://game.planetarion.com/waves.pl?id=$scantypes{$req->{type}}&x=$req->{x}&y=$req->{y}&z=$req->{z} "
	}

	$c->reply($text || 'No unhandled requests.');
}

sub scan
	: Help(syntax: scan type X:Y:Z [tick] | type is the first character in the scan name, like p for planet scan. Specify a tick if you want scans older than the specified tick.)
	: ACL(irc_scan)
	: Type(pm)
{
	my ($self, $c,$msg) = @_;

	my ($t, $x, $y, $z, $tick)
		= $msg =~ /^([pdunja]) (\d+)\D+(\d+)\D+(\d+)(?: (\d+))?/ or die 'ARGS';
	my $type =$scantypes[$scanid{$t}-1];

	my $scan = $c->model->selectrow_hashref(q{
SELECT id, scan_id, tick FROM scans
WHERE type = $1 AND planet = planetid($2,$3,$4,0) AND COALESCE(tick < $5,TRUE)
ORDER BY tick DESC LIMIT 1
			},undef,$type,$x,$y,$z,$tick);
	unless ($scan->{id}){
		$c->reply("No $type scan for $x:$y:$z. Planet might not exist.");
		return;
	}
	my $text = '';
	given ($t){
		when(/[ua]/){
			my $fid = $c->model->selectrow_array(q{
SELECT fid FROM fleet_scans WHERE id = $1
			},undef,$scan->{id});
			my $ships = $c->model->prepare(q{
SELECT ship,amount FROM fleet_ships WHERE fid = $1 ORDER BY num
			});
			$ships->execute($fid);
			while (my $ship = $ships->fetchrow_hashref){
				$text .= " $ship->{ship} $ship->{amount} |"
			}
		}
		default {
			$text = "http://game.planetarion.com/showscan.pl?scan_id=$scan->{scan_id}";
		}
	}
	$c->reply("<b>$type</b> scan of $x:$y:$z "
		. "($scan->{scan_id} pt: <b>$scan->{tick}</b>): $text");
}

1;
