package Vee::Controller::Users::Stats;

use strict;
use warnings;
use base 'Catalyst::Controller';

use List::Util qw/sum/;
use Vee::Utils::SVG;

=head1 NAME

Vee::Controller::Users - Statistics controller

=head1 SYNOPSIS

See L<Vee>

=head1 DESCRIPTION

Catalyst Controller for dealing with user-based statistics.  Includes forum
stats as well, since the forum is inherently user-based.

These are grouped together primarily because a lot of the generated charts are
their own SVG files included by <object> tags.

=head1 METHODS

=cut

=head2 index

=cut

sub index : Path {
    my ($self, $c) = @_;
    my $s = $c->stash;

    $s->{page_title} = 'User Statistics';
    $s->{extra_css}  = 'users';
    $s->{template}   = 'users/stats.tt';
}

=head2 top_posters

Returns an SVG pie chart of the top ten posters and the remaining bulk of posts.

=cut

sub top_posters : Path('top-posters.svg') {
    my ($self, $c) = @_;

    $c->res->content_type('image/svg+xml');

    my $posters_rs = $c->model('DBIC::Users')->search({
        post_count => { '!=', 0 },
    }, {
        order_by   => 'post_count DESC',
        rows       => 10,
        columns    => [qw[ name post_count ]],
    });
    # TODO: when we figure out what "counts" as a post, adjust this to compensate
    my $total_posts = $c->model('DBIC::Posts')->count;

    my @fields = $posters_rs->get_column('name')->all;
    my @data   = $posters_rs->get_column('post_count')->all;
    my $top_total = sum @data;
    if ($total_posts > $top_total) {
        push @fields, 'Everyone else';
        push @data,   $total_posts - $top_total;
    }
    
    $c->res->body( Vee::Utils::SVG::piechart(\@fields, \@data) );
}

=head2 loudmouths

Returns an SVG pie chart of the top ten shoutbox posters and the remaining bulk
of shouts.

=cut

sub loudmouths : Path('loudmouths.svg') {
    my ($self, $c) = @_;

    $c->res->content_type('image/svg+xml');

    my $loudmouths_rs = $c->model('DBIC::Shoutbox')->search(undef, {
        group_by  => 'user_id',
        '+select' => \'COUNT(*) AS shout_count',
        '+as'     => 'shout_count',
        order_by  => 'shout_count DESC',
        rows      => 10,
        columns   => [qw[ user.name ]],
        join      => 'user',
    });
    my $total_shouts = $c->model('DBIC::Shoutbox')->count;

    my @fields = map { $_->user->name                } $loudmouths_rs->all;
    my @data   = map { $_->get_column('shout_count') } $loudmouths_rs->all;
    my $top_total = sum @data;
    if ($total_shouts > $top_total) {
        push @fields, 'Everyone else';
        push @data,   $total_shouts - $top_total;
    }
    
    $c->res->body( Vee::Utils::SVG::piechart(\@fields, \@data) );
}

=head1 AUTHOR

Maintainer: Alex "Eevee" Munroe (C<veekun@veekun.com>)

See the included F<AUTHORS> file for a full list of contributers.

=head1 LICENSE

See the included F<LICENSE> file.

=cut

1;
