package Vote::Controller::Vote;

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

=head1 NAME

Vote::Controller::Vote - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

sub begin : Private {
    my ( $self, $c ) = @_;
    $c->model('Vote')->rollback;
}

sub index : Private {
    my ( $self, $c ) = @_;

    $c->stash->{template} = 'default.tt';
    $c->res->redirect($c->uri_for('/'));
}

sub default : LocalPath {
    my ( $self, $c, undef, $id ) = @_;

    $c->stash->{voteid} = $id;
    $c->stash->{page}{title} = 'Vote: ' . $c->model('Vote')->poll($id)->info('label');
}

sub report: LocalRegex('^(\w+)/(results|report).(\w+)$') {
    my ($self, $c) = @_;
    my $doc;
    ($c->stash->{voteid}, $doc, $c->stash->{format}) = @{ $c->req->snippets || [] };
    my $vote = $c->model('Vote');
    $c->stash->{template} = 'default.tt';

    $vote->poll($c->stash->{voteid})->info or do {
        $c->res->redirect($c->uri_for('/'));
        return;
    };
    # Ensure report is not availlable before end of poll
    if ($vote->poll($c->stash->{voteid})->status ne 'AFTER') {
        $c->res->redirect($c->uri_for('/vote', $vote->poll($c->stash->{voteid})->uid));
        return;
    };


    $c->stash->{template} = "poll_$doc.tt";
    $c->stash->{latex} = 1;
}

sub end : Private {
    my ($self, $c) = @_;
    if ($c->res->body) { return }
    elsif ($c->stash->{latex}) { $c->forward(qw/Vote::View::Latex/) }
    else { $c->forward(qw/Vote::View::TT/) }
}

=head1 AUTHOR

Thauvin Olivier

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself or CeCILL.

=cut

1;
