package SGO::Hiscore;
use 5.010;
use utf8;
use strict;
use warnings;

use Exporter qw(import);
our @EXPORT_OK = qw(
    get_hiscore_count_date
    get_hiscore_count_nick
    get_hiscores_date_limit
    hiscore_insert_h
);

use SGO qw(cache expire_cache get_dbh);

sub get_hiscores_date_limit {
    my ($date, $limit) = @_;
    my $cache_key = "hiscores-$date";
    $cache_key .= "-$limit" if $limit;
    cache($cache_key, sub {
        my $sql = <<SQL;
SELECT name, score, time, hints, check1, check2, timestamp, message, 
       total_count
    FROM hiscore WHERE date = ? ORDER BY total_count, score, time
SQL
        if ($limit) {
            $sql .= " LIMIT $limit";
        }
        get_dbh()->selectall_arrayref($sql, undef, $date);
    });
}

sub get_hiscore_count_date {
    my ($date) = @_;
    cache("hiscore_count-$date", sub {
        get_dbh()->selectrow_array('SELECT count(*) FROM hiscore WHERE date = ?', undef, $date);
    });
}

sub hiscore_insert_h {
    my %insert = @_;
    $insert{total_count} = $insert{hints} + $insert{check1} + $insert{check2};
    $insert{timestamp} = time;
    my @attrs = qw(time score hints check1 check2 name message date timestamp ip cheatlog alternations total_count);
    for my $attr (@attrs) {
        warn "Mssing argument '$attr' to hiscore_insert_h\n"
            unless defined $insert{$attr};
    }
    get_dbh()->do('INSERT INTO hiscore (' . join(', ', @attrs) . ') VALUES (' . join(', ', ('?') x @attrs) . ')',
                    undef,
                    @insert{@attrs},
                );
    my $date = $insert{date};
    expire_cache("hiscore_count-$date", "hiscore_average-$date", "hiscores-$date", "hiscores-$date-12", "hiscore_count_nick-$insert{name}");
}

sub get_hiscore_count_nick {
    my $nick = shift;
    cache("hiscore_count_nick-$nick", sub {
        my ($cnt) = get_dbh()->selectrow_array(
            'SELECT COUNT(*) FROM hiscore WHERE name = ?',
            undef,
            $nick,
        );
    });
}

1;
