package Newslash::Plugin::CustomBoxes;
use Mojo::Base 'Mojolicious::Plugin';
use DateTime;
use DateTime::Format::MySQL;

sub register {
    my ($self, $app, $conf) = @_;
    $self->{app} = $app;

    $app->helper(custom_boxes => sub { state $custom_boxes = $self });
}

sub query {
    my ($self, $model, $c, @rest) = @_;
    my $params = {@rest};

    return $self->_poll($params) if $model eq "poll";
    return $self->_mysite($params) if $model eq "mysite";
    return $self->_thisday($params) if $model eq "thisday";
    return;
}

sub app { return shift->{app}; }

sub _poll {
    my ($self, $params) = @_;
    my $polls = $self->app->model("polls");
    my $polls_config = $self->app->config("Polls") || {};
    my $limit_timestamp;

    if ($polls_config->{TTL} && 
        $polls_config->{TTL_unit} =~ m/\A(years|months|days|hours|minutes|seconds)\z/) {
        my $base_dt = DateTime->now;
        $base_dt->subtract($polls_config->{TTL_unit} => $polls_config->{TTL});

        $limit_timestamp = DateTime::Format::MySQL->format_datetime($base_dt);
    }

    my $poll = $polls->select(order_by => { create_time => "DESC" },
                              create_time => { gt => $limit_timestamp },
                              limit => 1);
    if ($poll) {
        return $poll;
    }
    return;
}

sub _mysite {
    my ($self, $params) = @_;
    my $user = $params->{_user} || {};
    my $my_links = $user->{config}->{ui}->{my_links};;
    $my_links = "" if !defined $my_links;

    return [$my_links];
}

sub _thisday {
    my ($self, $params) = @_;
    my $user = $params->{_user} || {};
    my $offset_sec = $user->{config}->{ui}->{offset_sec} || 0;
    my $stories = $self->app->model("stories");

    my $now = DateTime->now;
    $now->add(seconds => -$offset_sec) if $offset_sec;

    my @items;
    for (my $year = $now->year; $year > 2000; $year--) {
        my $rs = $stories->select(year => $year,
                                  month => $now->month,
                                  day => $now->day,
                                  offset_sec => $offset_sec,
                                  order_by => { hits => "DESC" },
                                  limit => 1,
                                 );
        if ($rs && @$rs) {
            $rs->[0]->{year} = $year;
            push @items, @$rs;
        }
    }
    my @rs = sort { $b->{hits} <=> $a->{hits} } @items;

    my $limit = $params->{limit} || 8;
    if (@rs > $limit) {
        @rs = @rs[0..$limit];
    }
    @rs = sort { $b->{year} <=> $a->{year} } @rs;

    return \@rs;
}

1;
