package Vote::DB::Voting;

# $Id$

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

=head1 NAME

Vote::Model::Vote - Catalyst Model

=head1 DESCRIPTION

Catalyst Model.

=cut

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

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

sub poll {
    my ($self) = @_;
    Vote::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
        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;

    $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 $passwd = Vote::DB::common::random_string(8);
    my $encpasswd = $self->gen_enc_passwd($passwd);
    my $upd_voting = $self->db->prepare_cached(
        q{update voting set passwd = ? where key = ?}
    );

    $upd_voting->execute($encpasswd, $self->votingkey);
    $self->db->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;
