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 begin : Private {
    my ( $self, $c, @args ) = @_;
    $c->model('Vote')->rollback;
}

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

    $c->res->redirect($c->uri_for('/'));
}

sub modify_poll : Private {
    my ( $self, $c) = @_;
    my $id = $c->stash->{voteid};

    my $poll = $c->model('Vote')->poll($id);
    for ($poll->status || '') {
    /^BEFORE$/ and do {
        if ($c->req->param('addch')) {
            $poll->add_choice($c->req->param('addch'))
                and $poll->commit;
        } elsif ($c->req->param('delch')) {
            $poll->delete_choice($c->req->param('delch'))
                and $poll->commit;
        } elsif ($c->req->param('pollparam')) {
            if ($c->req->param('dstart')) {
                $c->req->param('start',
                    $c->req->param('dstart') . ' ' . ($c->req->param('hstart') || '')
                );
            }
            if ($c->req->param('dend')) {
                $c->req->param('end',
                    $c->req->param('dend') . ' ' . ($c->req->param('hend') || '')
                );
            }
            if ($c->req->param('end') && $c->req->param('start')) {
                if ($poll->check_date_max($c->req->param('start'))) {
                    if (! $poll->check_date_max($c->req->param('end'), $c->req->param('start'))) {
                        $c->stash->{dateerror} = "Le vote se termine avant de commencer";
                        next;
                    }
                } else {
                    $c->stash->{dateerror} = "Le debut du vote doit être dans le futur";
                    next;
                }
            } elsif ($c->req->param('end') || $c->req->param('start')) {
                $c->stash->{dateerror} = "Vous devez définir un debut et une fin";
                next;
            }
            $poll->param(
                map { $_ => ($c->req->param($_) || undef) }
                grep { exists($c->req->params->{$_}) }
                qw(label description start end choice_count free_choice elected_count elected_choice)
            ) and $poll->commit;
        } elsif ($c->req->param('encrypted')) {
            my $passphrase = $c->req->param('passphrase') ||
                $c->session->{'vpass' . $c->stash->{voteid}};
            $poll->gen_poll_keys($passphrase)
                and $poll->commit;
        } elsif ($c->req->param('notcrypted')) {
            $poll->param(public_key => undef, private_key => undef)
                and $poll->commit;
        }
    };

    /^(BEFORE|RUNNING)$/ and do {
        if (my ($upload) = $c->req->upload('votinglist')) {
            $poll->voting_from_file(
                $upload->fh,
                $c->req->param('delete'),
            ) and $poll->commit;
        } elsif($c->req->param('delvoting')) {
            $poll->delete_voting($c->req->param('delvoting'))
                and $poll->commit;
        } elsif ($c->req->param('mail')) {
            $poll->addupd_voting($c->req->param('mail'), $c->req->param('id'))
                and $poll->commit;
        } elsif($c->req->param('mailpasswd')) {
            # TODO
            foreach my $vkey ($poll->list_voting_no_passwd) {
                my $voting = $poll->voting($vkey);
                my $pass = $voting->gen_passwd;
                $c->forward(
                    q'Vote::View::Mail', 'render',
                    [ 'voting_passwd.tt', {
                        From => $poll->info->{owner},
                        To => $voting->info->{mail},
                        Subject => "Invitation à voter",
                        mail => {
                            voteid => $id,
                            mail => $voting->info->{mail},
                            passwd => $pass,
                        }
                    } ]
                );
            }
        }
    };

    /^AFTER$/ and do {
        if ($c->req->param('mapfrom')) {
            $poll->map_value(
                $c->req->param('mapfrom'),
                $c->req->param('mapto') || undef,
            );
        }
        foreach my $bid ($poll->list_ballot_needvalid) {
            if (!$c->req->param($bid)) {
                next;
            } elsif($c->req->param($bid) eq 'invalid') {
                $poll->ballot($bid)->mark_invalid(1);
                $poll->commit;
            } elsif($c->req->param($bid) eq 'valid') {
                $poll->ballot($bid)->mark_invalid(0);
                $poll->commit;
            }
        }
        if ($c->req->param('decryptballot')) {
            my $passphrase = $c->req->param('passphrase') ||
                $c->session->{'vpass' . $c->stash->{voteid}};
            if ($c->model('Vote')->
                poll($c->stash->{voteid})->
                private_key($passphrase)) {
                $c->model('Vote')->poll($c->stash->{voteid})->decrypted_ballots(
                    $passphrase
                );
            } else {
            }
        }   
    };
    }
}

sub auth : Private {
    my ($self, $c) = @_;
    my $poll = $c->model('Vote')->poll($c->stash->{voteid});
    my $password = $c->session->{'vpass' . $c->stash->{voteid}} ||
        $c->req->param('vpass' . $c->stash->{voteid});

    if (!$poll->auth_poll($password)) {
        $c->stash->{page}{title} = $poll->info('label') .
            ': Login d\'administration';
        $c->session->{'vpass' . $c->stash->{voteid}} = undef;
        $c->stash->{template} = 'admin/login.tt';
        return;
    }
    $c->session->{'vpass' . $c->stash->{voteid}} = $password;
    return 1;
}

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

    $poll->info or do {
        $c->res->redirect($c->uri_for('/'));
        return;
    };

    $c->forward('auth') or return;
    $c->forward('modify_poll');
    $c->stash->{page}{title} = $poll->info('label') . ': Administration';
}

sub voting: LocalRegex('^(\w+)/voting$') {
    my ($self, $c) = @_;
    ($c->stash->{voteid}) = @{ $c->req->snippets || [] };
    my $poll = $c->model('Vote')->poll($c->stash->{voteid});

    $poll->info or do {
        $c->res->redirect($c->uri_for('/'));
        return;
    };

    $c->forward('auth') or return;
    $c->forward('modify_poll');
    $c->stash->{page}{title} = $poll->info('label') . ': Administration, liste des electeurs';
}

sub ballot: LocalRegex('^(\w+)/ballot$') {
    my ($self, $c) = @_;
    ($c->stash->{voteid}) = @{ $c->req->snippets || [] };
    my $poll = $c->model('Vote')->poll($c->stash->{voteid});

    $poll->info or do {
        $c->res->redirect($c->uri_for('/'));
        return;
    };

    $c->forward('auth') or return;
    $c->forward('modify_poll');
    $c->stash->{page}{title} = $poll->info('label') . ': Administration, bulletin';
}

sub privatekey : LocalRegex('^(\w+)/privatekey$') {
    my ($self, $c) = @_;
    ($c->stash->{voteid}) = @{ $c->req->snippets || [] };
    my $poll = $c->model('Vote')->poll($c->stash->{voteid});

    $poll->info or do {
        $c->res->redirect($c->uri_for('/'));
        return;
    };
    $c->response->body($poll->info('private_key') || '');
}

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;
