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

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

use Moose;
use MooseX::MethodAttributes;

sub adduser
	: Help(syntax: .+user username [pnick] | username must be alphanum characters, if no pnick is given then it will be set to the same as username)
	: Alias(+user)
	: ACL(irc_adduser)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$pnick) = $msg =~ /^(\w+)(?: ([^.\s]+))?$/ or die 'ARGS';
	$pnick //= $nick;

	my $dbh = $c->model;

	my $host = "$pnick.users.netgamers.org";
	my ($username,$hostname,$p_nick) = $dbh->selectrow_array(q{
SELECT username, hostmask,pnick
FROM users WHERE username ILIKE ? OR hostmask ILIKE ? OR pnick ILIKE ?
		},undef,$nick,$host,$pnick);

	if (defined $username){
		$c->reply("<b>$username ($p_nick)</b> already exists with host: <b>$hostname</b>");
	}else{
		$dbh->do(q{
INSERT INTO users (username,hostmask,pnick,password) VALUES(?,?,?,'')
		},undef,$nick,$host,$pnick);
		$c->reply("Added <b>$nick(/$pnick)</b> with host: <b>$host</b>");
	}
}

sub deactivateuser
	: Help(syntax: .-user nick | nick must be alphanum characters, if no pnick is given then it will be set to nick)
	: Alias(-user)
	: ACL(irc_deactivateuser)
{
	my ($self,$c,$msg) = @_;

	my ($nick) = $msg =~ /^(\S+)$/ or die 'ARGS';

	my $dbh = $c->model;
	my $f = $dbh->prepare(q{SELECT uid,username FROM users WHERE username ILIKE ?});
	$f->execute($nick);
	my ($uid,$username) = $f->fetchrow();

	if ($f->rows == 1){
		my $updated = $dbh->do(q{
UPDATE users SET hostmask = ?, password = '' WHERE uid = ?
		},undef,$username,$uid);
		if ($updated > 0){
			my $groups = $dbh->do(q{DELETE FROM groupmembers WHERE uid = ?},undef,$uid);
			$groups += 0;
			$c->reply("<b>$username</b> has been deactivated. Removed from $groups groups.");
		}else{
			$c->reply("Something went wrong when trying to modify <b>$username</b>");
		}
	}elsif ($f->rows == 0){
		$c->reply("No hit, maybe spelling mistake, or add % as wildcard");
	}else{
		$c->reply("More than 1 user matched, please refine the search");
	}
	$f->finish;
}

sub chattr
	: Help(syntax: .chattr username [-]flags | % can be used for wildcards \%arro% will match barrow, if a - is given then flags will be removed, otherwise added)
	: ACL(irc_chattr)
{
	my ($self,$c,$msg) = @_;

	my ($nick, $flags) = $msg =~ /^(\S+) ((\+|-)?\w+)$/ or die 'ARGS';
	my $dbh = $c->model;

	my $f = $dbh->prepare(q{SELECT uid,username FROM users WHERE username ILIKE ?});
	$f->execute($nick);
	my $user = $f->fetchrow_hashref;
	if ($f->rows == 1){
		my $update;
		if ($flags =~ /^(-)/){
			$update = $dbh->prepare(q{
DELETE FROM groupmembers WHERE uid = $1 AND
	gid IN (SELECT gid FROM groups WHERE flag = ANY($2))
			});
		}else{
			$update = $dbh->prepare(q{
INSERT INTO groupmembers (uid,gid) (SELECT $1,gid FROM groups
	WHERE flag = ANY($2) AND gid NOT IN (SELECT gid FROM groupmembers WHERE uid = $1))
			});
		}
		my @flags = split /\W*/,$flags;
		$update->execute($user->{uid},\@flags);
		$update = $dbh->prepare(q{
SELECT concat(flag)
FROM (SELECT uid,flag FROM groupmembers NATURAL JOIN groups ORDER BY uid,flag ) g
WHERE uid = ?
		});
		$flags = $dbh->selectrow_array($update,undef,$user->{uid});
		$c->reply("Flags for <b>$user->{username}</b> are now: $flags");
	}elsif ($f->rows == 0){
		$c->reply("No hit, maybe spelling mistake, or add % as wildcard");
	}else{
		$c->reply("More than 1 user matched, please refine the search");
	}
	$f->finish;
}

sub whois
	: Help(syntax: .whois [username] | % can be used for wildcards \%arro% will match barrow. If no username is given then all flags will be listed)
	: Alias(flags)
	: ACL(irc_whois)
{
	my ($self,$c,$msg) = @_;
	my ($nick) = $msg =~ /^(\S+)?$/ or die 'ARGS';
	my $dbh = $c->model;

	unless ($nick){
		my ($flags) = $dbh->selectrow_array(q{
SELECT TRIM(', ' FROM concat(flag||':'||groupname||', ')) FROM groups
		});
		$c->reply("Current flags: $flags");
		return;
	}

	my $f = $dbh->prepare(q{
SELECT username, pnick, hostmask, concat(flag) AS flags
FROM users u
	LEFT OUTER JOIN (SELECT uid,flag FROM groupmembers
		NATURAL JOIN groups ORDER BY uid,flag ) g USING (uid)
WHERE username ILIKE ?
GROUP BY username,pnick,hostmask LIMIT 5
		});
	$f->execute($nick);
	while (my $user = $f->fetchrow_hashref){
		$c->reply("<b>$user->{username} (/$user->{pnick})</b> flags: ($user->{flags}) host: $user->{hostmask}");
	}
	if ($f->rows == 0){
		$c->reply("No hit, maybe spelling mistake, or add % as wildcard");
	}
}

sub flag
	: Help(syntax: .flag flag | Lists all users with the given flag.)
	: ACL(irc_flag)
{
	my ($self,$c,$msg) = @_;
	my ($flag) = $msg =~ /^(\w)$/ or die 'ARGS';

	my $f = $c->model->prepare(q{
SELECT TRIM(', ' FROM concat(username||', ')),count(username)
FROM (SELECT uid, username FROM users ORDER BY username) u
	JOIN groupmembers gm USING (uid)
	JOIN groups g USING (gid)
WHERE flag = $1
		});
	my ($users,$count) = $c->model->selectrow_array($f,undef,$flag);
	$c->reply("<b>$count</b> Users with flag <b>$flag</b>: $users");
}

sub laston
	: Help(syntax: .laston flag [days] | lists users and the number of days since they were last seen (irc|forum|claim). If days is specified it will only list users with at least that amount of idle time. Days can also specify forum and claim with irc|forum|claim syntax)
	: ACL(irc_laston)
{
	my ($self,$c,$msg) = @_;
	my ($flag,$min,$forum,$claim) = $msg =~ /^(\w)(?: (\d+)(?:\|(\d+)\|(\d+))?)?$/
		or die 'ARGS';
	$min //= 0;

	my $f = $c->model->prepare(q{
SELECT username, COALESCE(last::text,'?') AS last
	,COALESCE(lastforum::text,'?') AS lastforum
	,COALESCE(lastclaim::text,'?') AS lastclaim
FROM (SELECT username
		,date_part('day',now() - laston)::int AS last
		,date_part('day',now() -
			(SELECT max(time) FROM forum_thread_visits WHERE uid = u.uid)) AS lastforum
		,date_part('day',now() -
			(SELECT max(timestamp) FROM raid_claims WHERE uid = u.uid)) AS lastclaim
	FROM users u
		NATURAL JOIN groupmembers
		NATURAL JOIN groups
	WHERE flag = $1
	) a
WHERE COALESCE(last >= $2,TRUE) AND COALESCE(lastforum >= $3,TRUE)
	AND COALESCE(lastclaim >= $4,TRUE)
ORDER BY last DESC, lastforum DESC, lastclaim DESC
		});
	$f->execute($flag,$min,$forum,$claim);

	my $text;
	my $i = 0;
	while (my $user = $f->fetchrow_hashref){
		$text .= "$user->{username}($user->{last}|$user->{lastforum}|$user->{lastclaim}) ";
		$i++;
	}
	$c->reply("<b>$i</b> Users(days) with flag <b>$flag</b>: $text");
}


sub lastseen
	: Help(syntax: .lastseen username | Shows the number of days since the user(s) last visited irc, forum and raids)
	: ACL(irc_lastseen)
{
	my ($self,$c,$msg) = @_;
	my ($username) = $msg =~ /^(\S+)$/ or die 'ARGS';

	my $f = $c->model->prepare(q{
SELECT username, COALESCE(date_part('day',now() - laston)::text,'?') AS last
	,COALESCE(date_part('day',now() - (SELECT max(time)
		FROM forum_thread_visits WHERE uid = u.uid))::text,'?') AS lastforum
	,COALESCE(date_part('day',now() - (SELECT max(timestamp)
		FROM raid_claims WHERE uid = u.uid))::text,'?') AS lastclaim
FROM users u
WHERE username ILIKE $1 ORDER BY lower(username)
		});
	$f->execute($username);

	my $text;
	my $i = 0;
	while (my $user = $f->fetchrow_hashref){
		$text .= "$user->{username}($user->{last}|$user->{lastforum}|$user->{lastclaim}) ";
		$i++;
	}
	$c->reply("<b>$i</b> Users(days): $text");
}

sub getships
	: Help(Usage: .getships ship | % can be used as wildcard, e.g. beet%, shipshome shows the number of ships currently home)
	: Alias(shipshome)
	: ACL(irc_getships)
{
	my ($self,$c,$msg) = @_;
	my ($ship) = $msg =~ /^(\S+)$/ or die 'ARGS';
	my $dbh = $c->model;

	my $f = $dbh->prepare(q{
SELECT username,SUM(fs.amount) AS amount
FROM users u
	JOIN (SELECT DISTINCT ON (planet) planet,fid FROM fleets
		WHERE mission = 'Full fleet' AND name <> 'Unit'
		ORDER BY planet,tick DESC,fid DESC
	) f  USING (planet)
	JOIN fleet_ships fs USING (fid)
WHERE ship ILIKE $1 AND uid IN (SELECT uid FROM groupmembers WHERE gid = 2)
GROUP BY username ORDER BY amount DESC
		});
	if ($self->name eq 'shipshome'){
		$f = $dbh->prepare(q{
SELECT username,SUM(amount) AS amount
FROM available_ships
WHERE ship ILIKE ? AND uid IN (SELECT uid FROM groupmembers WHERE gid = 2)
GROUP BY username ORDER BY amount DESC
		});
	}
	$f->execute($ship);
	my $text;
	my $i = 0;
	my $total = 0;
	while (my $user = $f->fetchrow_hashref){
		$text .= "$user->{username}: $user->{amount} ";
		$i++;
		$total += $user->{amount};
	}
	if ($text){
		$c->reply("<b>$i</b> Users with <b>$total $ship</b>: $text");
	}else{
		$c->reply("Couldn't find any user with <b>$ship</b>");
	}
}

sub getfleet
	: Help(Usage: .getfleet username | % can be used as wildcard, e.g. barr%)
	: ACL(irc_getfleet)
{
	my ($self,$c,$msg) = @_;
	my ($nick) = $msg =~ /^(\S+)$/ or die 'ARGS';
	my $dbh = $c->model;

	my $f = $dbh->prepare(q{
SELECT fs.ship, fs.amount, username
FROM fleet_ships fs
	JOIN (SELECT fid,username
		FROM fleets f
			JOIN users u USING (planet)
		WHERE mission = 'Full fleet' AND name <> 'Unit'
			AND username ILIKE $1
		ORDER BY planet,tick DESC,fid DESC
		LIMIT 1
	) f  USING (fid)
ORDER BY num
		});
	$f->execute($nick);
	my $text;
	my $username;
	while (my $ship = $f->fetchrow_hashref){
		unless (defined $username) {
			$username = $ship->{username};
			$text = "<b>$username</b> has: "
		}
		$text .= "$ship->{ship} $ship->{amount} ";
	}
	if ($text){
		$c->reply($text);
	}else{
		$c->reply("Couldn't find any fleet for $nick");
	}
}

sub sethost
	: Help(Usage: .sethost username [host] | if host isn't given then it resets to netgamers host)
	: ACL(irc_sethost)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$host) = $msg =~ /^(\S+)(?: (\S+))?$/ or die 'ARGS';
	my $dbh = $c->model;

	my $f = $dbh->prepare(q{
SELECT uid,username,pnick,hostmask FROM users WHERE username ILIKE ?
		});
	$f->execute($nick);
	my $user = $f->fetchrow_hashref;
	if ($f->rows == 1){
		$host //= "$user->{pnick}.users.netgamers.org";
		eval{
			$dbh->do(q{UPDATE users SET hostmask = ? WHERE uid = ?}
				,undef,$host,$user->{uid});
			$c->reply("Updated <b>$user->{username}</b>'s host to: <b>$host</b>");
		};
		if($@){
			if ($@ =~ /duplicate key value violates unique constraint/){
				my ($username, $hostname) = $dbh->selectrow_array(q{
SELECT username,hostmask FROM users WHERE hostmask ILIKE $1
				},undef,$host);
				$c->reply("<c04>Problem</c>, <b>$username</b> already uses host <b>$hostname</b>.");
			}else{
				die $@;
			}
		}
	}elsif ($f->rows == 0){
		$c->reply("No hit, maybe spelling mistake, or add % as wildcard");
	}else{
		$c->reply("More than 1 user matched, please refine the search");
	}
	$f->finish;
}

sub setpnick
	: Help(Usage: .setpnick username pnick | Changes a user's pnick)
	: ACL(irc_setpnick)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$pnick) = $msg =~ /^(\S+) (\S+)$/ or die 'ARGS';
	my $dbh = $c->model;

	my $f = $dbh->prepare(q{SELECT uid,username FROM users WHERE username ILIKE ?});
	$f->execute($nick);
	my $user = $f->fetchrow_hashref;
	if ($f->rows == 1){
		my $hostname = "$pnick.users.netgamers.org";
		eval{
			$dbh->do(q{UPDATE users SET pnick = ?, hostmask = ? WHERE uid = ?}
				,undef,$pnick,$hostname,$user->{uid});
			$c->reply("Updated <b>$user->{username}</b>'s pnick to: <b>$pnick</b> and hostname to <b>$hostname</b>");
		};
		if($@){
			if ($@ =~ /duplicate key value violates unique constraint/){
				my ($username, $hostname, $pnick) = $dbh->selectrow_array(q{
SELECT username,hostmask,pnick FROM users WHERE hostmask ILIKE $1 OR pnick ILIKE $2
				},undef,$hostname, $pnick);
				$c->reply("<c04>Problem</c>, <b>$username</b> already uses host <b>$hostname</b> and pnick <b>$pnick</b>.");
			}else{
				die $@;
			}
		}
	}elsif ($f->rows == 0){
		$c->reply("No hit, maybe spelling mistake, or add % as wildcard");
	}else{
		$c->reply("More than 1 user matched, please refine the search");
	}
	$f->finish;
}

sub a
	: Help(Usage: .a username [points] | % can be used for wildcards \%arro\% will match barrow, if the number of points isn't specified, then 1 will be assumed.)
	: ACL(irc_a)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$points) = $msg =~ /^(\S+)(?: (-?(\d+)?(\.\d+)?))?$/ or die 'ARGS';
	$points //= 1;

	my ($fleets) = $c->model->selectrow_array(q{
SELECT count(*) FROM raids r
	JOIN raid_targets rt ON r.id = rt.raid
	JOIN raid_claims rc ON rt.id = rc.target
WHERE not launched  AND tick + 24 > tick()
	AND uid = (SELECT uid FROM users WHERE username ILIKE $1);
		},undef,$nick);

	if ($fleets > 0 && $points > 0){
		$c->reply("$nick has $fleets claimed waves the last 24 ticks that aren't marked as launched, so no points.");
		return;
	}
	addPoints($c, 'attack', $nick, $points);
}

sub d
	: Help(Usage: .d username [points] | % can be used for wildcards \%arro\% will match barrow, if the number of points isn't specified, then 1 will be assumed.)
	: ACL(irc_d)
	: Type(def)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$points) = $msg =~ /^(\S+)(?: (-?(\d+)?(\.\d+)?))?$/ or die 'ARGS';

	addPoints($c, 'defense', $nick, $points);
}

sub s
	: Help(Usage: .s username [points] | % can be used for wildcards \%arro\% will match barrow, if the number of points isn't specified, then 1 will be assumed.)
	: ACL(irc_s)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$points) = $msg =~ /^(\S+)(?: (-?(\d+)?(\.\d+)?))?$/ or die 'ARGS';

	addPoints($c, 'scan', $nick, $points);
}

sub h
	: Help(Usage: .h username [points] | % can be used for wildcards \%arro\% will match barrow, if the number of points isn't specified, then 1 will be assumed.)
	: ACL(irc_h)
{
	my ($self,$c,$msg) = @_;
	my ($nick,$points) = $msg =~ /^(\S+)(?: (-?(\d+)?(\.\d+)?))?$/ or die 'ARGS';

	addPoints($c, 'humor', $nick, $points);
}

sub addPoints {
	my ($c,$type, $nick, $points) = @_;
	$points //= 1;

	my $dbh = $c->model;

	if ($points*$points > 400){
		$c->reply("Values between -20 and 20 please");
		return;
	}

	my $f = $dbh->prepare(q{SELECT uid,username FROM users WHERE username ILIKE ?});
	$f->execute($nick);
	my $user = $f->fetchrow_hashref;
	if ($f->rows == 1){
		$type .= "_points";
		$dbh->do(qq{UPDATE users SET $type = $type + ? WHERE uid = ?}
			,undef,$points,$user->{uid});
		$c->reply("$user->{username} has been given $points $type");
	}elsif ($f->rows == 0){
		$c->reply("No hit, maybe spelling mistake, or add % as wildcard");
	}else{
		$c->reply("More than 1 user matched, please refine the search");
	}
	$f->finish;
}

1;
