package Vote::DB::Ballot;

# $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, $id) = @_;
    
    bless {
        id => $id,
        dbstring => $dbstring,
        db => Vote::DB::common::_newdb($dbstring),
    }, $class;
}

sub ballotid { $_[0]->{id} }

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 * from 
           ballot left join 
           ballot_enc on ballot.id = ballot_enc.id 
           where ballot.id = ? }
    );

    $sth->execute($self->ballotid);
    my $res = $sth->fetchrow_hashref;
    $sth->finish;
    $res
}

sub mark_invalid {
    my ($self, $invalid) = @_;

    my $sth = $self->db->prepare_cached(
        q{update ballot set invalid = ? where id = ?}
    );

    $sth->execute($invalid ? 't' : 'f', $self->ballotid);
}

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

    my $sth = $self->db->prepare_cached(
        q{select *, value as v from ballot_item where id = ?}
    );
    $sth->execute($self->ballotid);
    my @ids;
    while (my $res = $sth->fetchrow_hashref) {
        push(@ids, $res);
    }
    \@ids
}

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