package ParadisePoker::Tournament::Database;
use strict;
use warnings;

use DBI qw(:sql_types);

use constant DB_CONNECT => 'dbi:Pg:dbname=marshall';

my %tourney_binding = (start_hand  => SQL_INTEGER,
                       start_time  => SQL_VARCHAR,
                       finish_hand => SQL_INTEGER,
                       finish_time => SQL_VARCHAR,
                       table_name  => SQL_VARCHAR,
                       game        => SQL_VARCHAR,
                       prize_pool  => SQL_NUMERIC,
                       buyin       => SQL_NUMERIC,
                       fee         => SQL_NUMERIC,
                       originator  => SQL_VARCHAR);

my $dbh = DBI->connect(DB_CONNECT) or die $DBI::errstr;

sub insert($) {
  my $hashref = shift;

  my $sth =
    $dbh->prepare("insert into pp2_tournaments
                   (@{[join ',' => keys %tourney_binding]})
                   values (@{[join ',' => ('?') x keys %tourney_binding]})")
      or die $dbh->errstr;
  for (my $i = 1; my ($col, $binding) = each %tourney_binding; $i++) {
    $sth->bind_param($i, $hashref->{$col}, $binding) or die $sth->errstr;
  }
  $sth->execute or die $sth->errstr;
  _insert_finishes($hashref->{start_hand}, $hashref->{results});
}

sub _insert_finishes($$) {
  my $start_hand = shift;
  my $aryref     = shift;

  my $sth =
    $dbh->prepare("insert into pp2_finishes
                   (tournament, player, place, last_hand, prize)
                   values ($start_hand, ?, ?, ?, ?)") or die $dbh->errstr;
  foreach my $finish (@$aryref) {
    $sth->bind_param(1, $finish->{name},             SQL_VARCHAR)
      or die $sth->errstr;
    $sth->bind_param(2, $finish->{place},            SQL_INTEGER)
      or die $sth->errstr;
    $sth->bind_param(3, $finish->{last_hand_number}, SQL_INTEGER)
      or die $sth->errstr;
    $sth->bind_param(4, $finish->{prize},            SQL_NUMERIC)
      or die $sth->errstr;
    $sth->execute or die $sth->errstr;
  }
}

sub already_present($) {
  my $hashref = shift;

  my $sth =
    $dbh->prepare("select count(*)
                   from pp2_tournaments
                   where start_hand = ?") or die $dbh->errstr;
  $sth->bind_param(1, $hashref->{start_hand}, SQL_INTEGER) or die $sth->errstr;
  $sth->execute or die $sth->errstr;
  my @result = $sth->fetchrow_array or die $sth->errstr;
  $result[0] ? 1 : 0;
}

1;

