#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::DB::RoyaltyRunItem;

use strict;
use warnings;
use Carp;
use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::DB::Item;
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::RoyaltyRun::Status;

use base 'Common::DB::Item';

use constant kDB => Common::DB::Item::kClientDB();

use constant kOpenRunStatus => [
    RPS::RoyaltyRun::Status::kComplete,     RPS::RoyaltyRun::Status::kRunning,
    RPS::RoyaltyRun::Status::kWaitingToRun, RPS::RoyaltyRun::Status::kWaitingToCommit
];

sub _GenerateClassConfig {
    my ($class) = @_;

    my $config = $class->SUPER::_GenerateClassConfig();

    $config->{_running}           = { _readOnly => 1 };
    $config->{_complete}          = { _readOnly => 1 };
    $config->{_committed}         = { _readOnly => 1 };
    $config->{_aborted}           = { _readOnly => 1 };
    $config->{_error}             = { _readOnly => 1 };
    $config->{_closed}            = { _readOnly => 1 };
    $config->{_waiting_to_run}    = { _readOnly => 1 };
    $config->{_waiting_to_commit} = { _readOnly => 1 };
    $config->{_waiting_to_delete} = { _readOnly => 1 };
    $config->{_invalidated}       = { _readOnly => 1 };

    return $config;
}

sub _openRunStatusClause {
    my $status = kOpenRunStatus;
    return "status in (" . join( ",", @$status ) . ")";
}

sub _table { assert( 0, "Must be overloaded" ) }

# override to order by start_time
#
sub GetAll {
    my ($class) = @_;
    $class->_openRunStatusClause();

    my $sql = "SELECT * FROM " . $class->_table() . " ORDER BY start_time DESC";

    return $class->SUPER::GetAll($sql);
}

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

    my $sql = "SELECT * FROM " . $class->_table();

    my @where;

    if ( $args{payor} ) {
        push @where, "payor_id = " . $class->quote( $args{payor} );
    }

    if ( defined $args{status} ) {
        push @where, "status = " . $class->quote( $args{status} );
    }

    if ( scalar @where ) {
        my $whereClause = "WHERE " . join( ' AND ', @where );
        $sql .= " " . $whereClause;
    }

    $sql .= " ORDER BY CASE";
    $sql .= " WHEN start_time = '0000-00-00 00:00:00' THEN '9999-99-99 23:59:59'";
    $sql .= " ELSE start_time END";
    $sql .= " DESC";

    return $class->SUPER::GetAll($sql);
}

# We need this for the GetOtherCommittedRuns method.
#
sub GetAllLegacy {
    my ( $class, $sql ) = @_;

    return $class->SUPER::GetAll($sql);
}

sub GetRunStatusCounts {
    my $class = shift;
    my %args  = @_;

    my $payorID   = $args{payorID};
    my $sinceDate = $args{sinceDate};

    my $sql =
        "SELECT "
      . "COUNT(IF (status = 0, 1, NULL)) as _running, "
      . "COUNT(IF (status = 1, 1, NULL)) as _complete, "
      . "COUNT(IF (status = 2, 1, NULL)) as _committed, "
      . "COUNT(IF (status = 3, 1, NULL)) as _aborted, "
      . "COUNT(IF (status = 4, 1, NULL)) as _error, "
      . "COUNT(IF (status = 5, 1, NULL)) as _closed, "
      . "COUNT(IF (status = 6, 1, NULL)) as _waiting_to_run, "
      . "COUNT(IF (status = 7, 1, NULL)) as _waiting_to_commit, "
      . "COUNT(IF (status = 8, 1, NULL)) as _waiting_to_delete, "
      . "COUNT(IF (status = 9, 1, NULL)) as _invalidated " . "FROM "
      . $class->_table();

    my @where;

    if ($payorID) {
        push @where, "payor_id = " . $class->quote($payorID);
    }
    if ($sinceDate) {
        push @where, "start_time > " . $class->quote($sinceDate);
    }
    if ( scalar @where ) {
        $sql .= ' WHERE ' . join( ' AND ', @where );
    }
    Common::Log::Debug("QUERY: $sql");
    my $list = $class->SUPER::GetAll($sql);

    return $list->next;
}

sub GetOpenRunCount {
    my ( $class, $payorID ) = @_;
    my $dbo = Common::RSApp::GetClientDB();

    my $sql = "SELECT count(*) from " . $class->_table() . " WHERE " . $class->_openRunStatusClause();

    if ($payorID) {
        $sql .= " AND payor_id = " . $dbo->DBQuote($payorID);
    }

    my $sth = $dbo->DoCmd($sql);
    my ($count) = $sth->fetchrow_array();

    return $count;
}

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

    my $sql = "SELECT * FROM " . $class->_table();

    my $dbo = Common::RSApp::GetClientDB();

    if ( $args{query} ) {
        $sql .= " WHERE date_modified >= " . $dbo->DBQuote( $args{query} );
    }

    return $class->SUPER::GetAll($sql);
}

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

    my $sql = "SELECT * FROM (SELECT count(*) as total, ";

    my $dbo = Common::RSApp::GetClientDB();

    if ( $args{query} ) {
        $sql .= ' count(if( date_modified >= ' . $dbo->DBQuote( $args{query} ) . ', 1, NULL )) as count';
    } else {
        $sql .= " count(*) as count ";
    }

    $sql .= " FROM " . $class->_table();
    $sql .= ") as subq WHERE count = 0 AND total > 0";

    return $class->SUPER::GetAll($sql);
}

1;
