package Vote::Controller::Admin;

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

=head1 NAME

Vote::Controller::Admin - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

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

}

sub default : Private {
    my ( $self, $c, undef, $id ) = @_;
    $c->stash->{voteid} = $id;
    my $vote = $c->model('Vote');

    my $password = $c->session->{vpassword} || $c->req->param('vpassword');

    if (!$c->model('Vote')->auth_poll($id, $password)) {
        $c->session->{vpassword} = undef;
        $c->stash->{template} = 'admin/login.tt';
        return;
    }

    $c->session->{vpassword} = $password;

    if ($vote->vote_status($id) eq 'BEFORE') {
        if (my ($upload) = $c->req->upload('votinglist')) {
            $vote->voting_from_file(
                $id,
                $upload->fh,
                $c->req->param('delete'),
            ) and $vote->db->commit;
        } elsif ($c->req->param('addch')) {
            $vote->vote_add_choice($id, $c->req->param('addch'))
                and $vote->db->commit;
        } elsif ($c->req->param('delch')) {
            $vote->delete_choice($c->req->param('delch'))
                and $vote->db->commit;
        } elsif ($c->req->param('label')) {
            $vote->vote_param(
                $id,
                map { $_ => ($c->req->param($_) || undef) }
                qw(label description start end choice_count free_choice)
            ) and $vote->db->commit;
        } elsif($c->req->param('delvoting')) {
            $vote->delete_voting($c->req->param('delvoting'))
                and $vote->db->commit;
        } elsif ($c->req->param('mail')) {
            $vote->addupd_voting($id, $c->req->param('id'), $c->req->param('mail'))
                and $vote->db->commit;
        } elsif($c->req->param('mailpasswd')) {
            $vote->mail_passwd_ifnul($id);
        }
    } elsif ($vote->vote_status($id) eq 'AFTER') {
        foreach my $bid ($vote->list_vote_ballot_needvalid($id)) {
            if (!$c->req->param($bid)) {
                next;
            } elsif($c->req->param($bid) eq 'invalid') {
                $vote->mark_ballot_invalid($bid, 1);
                $vote->db->commit;
            } elsif($c->req->param($bid) eq 'valid') {
                $vote->mark_ballot_invalid($bid, 0);
                $vote->db->commit;
            }
        }
    } else {
        # can't modify vote after date
        $c->stash->{template} = 'admin/denied.tt';
        return;
    }

}

=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.

=cut

1;
