package Epoll::DB::Voting;

# $Id$

use strict;
use warnings;
use base 'Epoll::DB::common';
use Epoll::DB::Poll;

=head1 NAME

Epoll::DB::Voting - Catalyst Model

=head1 DESCRIPTION

Catalyst Model.

=cut

sub new {
    my ($class, $dbstring, $key) = @_;
    
    bless {
        key => $key,
        dbstring => $dbstring,
        db => Epoll::DB::common::_newdb($dbstring),
    }, $class;
}

sub votingkey { $_[0]->{key} }

sub poll {
    my ($self) = @_;
    Epoll::DB::Poll->new($self->{dbstring}, $self->info->{poll});
}

sub info {
    my ($self) = @_;

    my $sth = $self->db->prepare_cached(
        q{
        select *, voting.key as vkey from voting left join signing
        on signing.key = voting.key
        left join extern_auth on voting.extern_auth = extern_auth.id
        where voting.key = ?
        }
    );
    $sth->execute($self->votingkey);

    my $res = $sth->fetchrow_hashref;
    $sth->finish;
    $res
}

sub auth {
    my ($self, $password) = @_;
    my $userinfo = $self->info or return;

        warn "ee";
    if ($userinfo->{extern_uid}) {
        warn "rr";
        my $handle = $self->stored_import_handle($userinfo->{extern_auth})
            or return;
        return $handle->authenticate($userinfo->{mail}, $userinfo->{extern_uid}, $password);
    } else {
        $userinfo->{passwd} or return;
        if (crypt($password, $userinfo->{passwd} || '') eq $userinfo->{passwd}) {
            return 1;
        } else {
            return 0;
        }
    }
}

sub has_sign {
    my ($self) = @_;

    my $sth = $self->db->prepare_cached(
        q{
        select date from signing join voting
        on voting.key = signing.key
        where voting.key = ?
        }
    );

    $sth->execute($self->votingkey);
    my $res = $sth->fetchrow_hashref;
    $sth->finish;
    return $res->{date}
}

sub gen_passwd {
    my ($self) = @_;
    my $info = $self->info;
    my $passwd;
    my $upd_voting = $self->db->prepare_cached(
        q{update voting set passwd = ? where key = ?}
    );
    if ($info->{extern_auth}) {
        $upd_voting->execute('EXTERN_AUTH', $self->votingkey);
        $passwd = $info->{desc} || $info->{auth_type};
    } else {
        $passwd = Epoll::DB::common::random_string(8);
        my $encpasswd = $self->gen_enc_passwd($passwd);

        $upd_voting->execute($encpasswd, $self->votingkey);
    }
    $self->commit;
    $passwd
}

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