package Epoll::Controller::Admin;

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

=head1 NAME

Epoll::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('polldate')) {
            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} = $c->localize('The vote finish before starting');
                        next;
                    }
                } else {
                    $c->stash->{dateerror} = $c->('The start of the vote must be in the future');
                    next;
                }
            } elsif ($c->req->param('end') || $c->req->param('start')) {
                $c->stash->{dateerror} =  $c->localize('You must define a start and a end date');
                next;
            }
            $poll->param(
                map { $_ => ($c->req->param($_) || undef) }
                grep { exists($c->req->params->{$_}) }
                qw(start end)
            ) and $poll->commit;
        } elsif ($c->req->param('pollparam')) {
            $poll->param(
                map { $_ => ($c->req->param($_) || undef) }
                qw(label description procedure
                no_mail_confirm_vote no_ballot_id_voting no_mail_ballot_id
                )
            ) and $poll->commit;
        } elsif ($c->req->param('pollballot')) {
            $poll->param(
                map { $_ => ($c->req->param($_) || undef) }
                qw(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;
        }
    };

    /^AFTER$/ and do {
        if ($c->req->param('mapfrom')) {
            $poll->map_value(
                $c->req->param('mapfrom'),
                $c->req->param('mapto') || undef,
            );
        }
        foreach my $bid ($c->req->param('bsubvalid')) {
            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}};
                $c->model('Vote')->poll($c->stash->{voteid})->decrypted_ballots(
                    $passphrase
                );
        }
        if ($c->req->param('publish')) {
            $c->model('Vote')->poll($c->stash->{voteid})->compute_results;
            $c->model('Vote')->commit;
            $c->res->redirect($c->uri_for('/vote', $poll->uid));
        }   
    };
    }
}

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

    my $poll = $c->model('Vote')->poll($c->stash->{voteid});
    $c->req->params->{ballotvalue} = 's:needvalid'
        if (!$c->req->param('ballotvalue'));

    for ($c->req->param('ballotvalue') || '') {
        /^v:(.*)/ and $c->stash->{ballotfilter} =
            [ $poll->ballot_by_value($1) ];
        /^s:invalid$/ and $c->stash->{ballotfilter} =
            [ $poll->list_ballot_invalid ];
        /^s:valid$/ and $c->stash->{ballotfilter} =
            [ $poll->list_ballot_valid ];
        /^s:needvalid$/ and $c->stash->{ballotfilter} =
            [ $poll->list_ballot_needvalid ];
    }
}

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

    if (!$poll->auth_poll($password)) {
        $c->stash->{page}{title} = $poll->info('label') .
            . ': ' . $c->localize('Administrator login');
        $c->session->{'vpass' . $c->stash->{voteid}} = undef;
        $c->stash->{template} = 'admin/login.tt';
        return;
    }
    $c->session->{'vpass' . $poll->uid} = $password;
    $c->session_expire_key( 'vpass' . $poll->uid => 1800 );
    $c->session->{mypoll}{$poll->uid} = 1;
    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') . ': ' . $c->localize('Administration');
}

sub voters: LocalRegex('^(\w+)/voters$') {
    my ($self, $c) = @_;
    ($c->stash->{voteid}) = @{ $c->req->snippets || [] };
    my $id = $c->stash->{voteid};
    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;
    
    for ($poll->status || '') {
        /^(BEFORE|RUNNING)$/ and do {
            if($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'Epoll::View::Mail', 'render',
                        [ 'voting_passwd.tt', {
                            From => $poll->info->{owner},
                            To => $voting->info->{mail},
                            Subject => $c->localize("Voting invitation"),
                            mail => {
                                voteid => $id,
                                mail => $voting->info->{mail},
                                passwd => $pass,
                            }
                        } ]
                    );
                }
            }
        };
    }

    $c->stash->{page}{title} = $poll->info('label') . ': ' . $c->localize('Administration') . ', ' . $c->localize('voters list');
}

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

    if ($c->req->param('importtype')) {
        if (my $handle = $poll->import_handle($c->req->param('importtype'))) {
            $c->stash->{import_handle} = $handle;
            if ($c->req->param('add_import')) {
                warn $c->session->{import_param};
                $handle->load_xml_params($c->session->{import_param});
                if ($poll->voting_from_import($handle,
                        ext_auth => $c->req->param('ext_auth') || undef,
                        desc => $c->req->param('desc') || undef,
                    )) {
                    $poll->commit;
                    $c->res->redirect($c->uri_for($c->stash->{voteid},
                            'voters'));
                    return;
                }
            } else {
                $handle->load_web_params($c);
            }
            $c->stash->{voters} = [ $handle->fetch_voters() ];
            $c->{stash}->{importtt} = 'importv/' .
                lc($c->req->param('importtype')) . '.tt';
            warn $handle->xml_params;
            $c->session->{import_param} = $handle->xml_params;
        } else {
            warn "Fail to load input handle";
        }
    }

}

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') . ': ' . $c->localize('Administration') . ', '. $->l('ballots');
}

sub date: LocalRegex('^(\w+)/date$') {
    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') . ': ' . $c->localize('Administration') . ', '. $c->localize('Date');
}

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 validate: LocalRegex('^(\w+)/validate$') {
    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') . ': ' . $c->localize('Administration') . ', ' . $c->localize('Validation');

    $c->forward('ballotfilter');
}

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

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

    $c->forward('auth') or return;

    if ($c->req->param('delete_ballot')) {
        $c->stash->{template} = 'admin/delete_ballot_confirm.tt';
        return;
    }
    
    if ($c->req->param('delete_poll')) {
        $c->stash->{template} = 'admin/delete_poll_confirm.tt';
        return;
    }

    if ($c->req->param('delete_ballot_confirm')) {
        $poll->delete_ballots;
        $c->response->redirect($c->uri_for($poll->uid));
    }

    if ($c->req->param('delete_poll_confirm')) {
        $c->model('Vote')->delete_poll($poll->voteid);
        $c->response->redirect($c->uri_for('/'));
        $c->detach;
    }
}

sub ajaxsettings: LocalRegex('^(\w+)/ajaxsettings$') {
    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->stash->{ajax} = 1;
    $c->stash->{pollsettings} = $c->req->params;
    $c->stash->{template} = 'admin/includes/poll_extra_settings.tt';
}

sub end : Private {
    my ($self, $c) = @_;
    if ($c->res->body) { return }
    elsif ($c->stash->{latex}) { $c->forward(qw/Epoll::View::Latex/) }
    elsif ($c->stash->{ajax}) { $c->forward(qw/Epoll::View::Ajax/) }
    else { $c->forward(qw/Epoll::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;
