package App::POS::DB::Postgres;

use strict;
use warnings;
use Data::Dumper;
use File::Copy qw( move copy );
use FindBin qw( $Bin );
use POSIX qw( strftime );

use base qw( App::POS::DB );

my %partitioned_tables = (
  sales_details => 1,
  sales_hashes => 1,
  sales_hashes_products => 1,
  sales_headers => 1,
  sales_payments => 1,
);

sub register_functions {
}

sub next_id {
  my $s = shift;
  my( $table ) = @_;
  my $dbh = $s->dbh();

  if (exists $partitioned_tables{$table}) {
    my $table = $table . "_" . strftime("%Y%m", localtime);

    eval {
      my $sth = $dbh->prepare("SELECT MAX(id) AS max_id FROM $table");
      $sth->execute();

      my $max = 0;

      while (my $rec = $sth->fetchrow_hashref) {
        $rec->{max_id} ||= 0;
        $max = $rec->{max_id}+1;
      }

      if ($max != 0) {
        return $max,
      }
    };
  }

  my $sth = $dbh->prepare("SELECT MAX(id) AS max_id FROM $table");
  $sth->execute();

  my $max = 0;

  while (my $rec = $sth->fetchrow_hashref) {
    $rec->{max_id} ||= 0;
    $max = $rec->{max_id}+1;
  }

  $max ||= 1;
  return $max;
}

sub table_fields {
  my $s = shift;
  my $t = shift || undef;

  my @r = ();

  if (defined $t) {
    @r = $s->select(qq{
      SELECT attname
        FROM pg_attribute
       WHERE attrelid=(SELECT oid FROM pg_class WHERE relname=?) AND attnum > 0 AND atttypid > 0;
    }, $t);
  }

  return wantarray? @r : \@r;
}

sub set_work_mem {
  my $self = shift;
  my $mem = shift;

  $self->dbh->do(qq{SET work_mem TO $mem});
}

sub analyze_table {
  my $self = shift;
  my $table = shift;

  $self->dbh->do(qq{ANALYZE $table});
}

sub vacuum_analyze_table {
  my $self = shift;
  my $table = shift;

  $self->dbh->do(qq{REINDEX TABLE $table});
  $self->dbh->do(qq{ANALYZE $table});
}

1;

