package Vote::DB::Poll::Results;

# $Id$

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

=head1 NAME

Vote::Model::Vote - Catalyst Model

=head1 DESCRIPTION

Catalyst Model.

=cut

sub new {
    my ($class, %args) = @_;

    my $res = $class->SUPER::new(%args);
    
    return bless $res, $class;
}

sub absolute_majority {
    my ($self) = @_;
    my $ballot_count = $self->ballot_count_nonull;
    return int($ballot_count / 2) + 1;
}    

sub abstention {
    my ($self) = @_;
    
    my $sth = $self->db->prepare_cached(
        q{
        select count(*) from ballot where poll = ?
        and id not in (select id from ballot_item) and
        (invalid = 'false' or invalid is null)
        }
    );

    $sth->execute($self->voteid);
    my $res = $sth->fetchrow_hashref;
    $sth->finish;
    $res->{count}
}

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

    my $sth = $self->db->prepare_cached(
        q{
        select count(*) from ballot where poll = ?
        and id in (select id from ballot_item) and
        (invalid = 'false' or invalid is null)
        }
    );

    $sth->execute($self->voteid);
    my $res = $sth->fetchrow_hashref;
    $sth->finish;
    $res->{count}
}

sub results_count {
    my ($self) = @_;
    $self->_results();
}

sub results_nonull {
    my ($self) = @_;
    $self->_results(1);
}

sub _results {
    my ($self, $nonull) = @_;

    my $sth = $self->db->prepare(
        q{
        select count(ballot.id), value from
        (
        select NULL as id, label as value from choice where poll = ?
        union
        select ballot.id, coalesce(corrected, ballot_map.to, value) as "value" from ballot
        } . ($nonull ? '' : ' left ') . q{
        join ballot_item
        on ballot.id = ballot_item.id 
        left join ballot_map on ballot.poll = ballot_map.poll and ballot_map.from = ballot_item.value
        where ballot.poll = ? and (invalid = 'false' or invalid is null
        )
        group by ballot.id, coalesce(corrected, ballot_map.to, value)) as ballot
        group by value
        order by count desc, value
        }
    );
    $sth->execute($self->voteid, $self->voteid);
    my @results;
    while (my $res = $sth->fetchrow_hashref) {
        push(@results, $res);
    }
    \@results;
}

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