#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#---------------------------------------------------------------
package BookPub::DB::Item::CatalogImport;

use strict;
use warnings;

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

use constant kTable => 'catalog_import';
use constant kDB    => Common::DB::Item::kClientDB;

# Ready states
#
use constant kImportStatusFetchReady    => 'WFCH';
use constant kImportStatusStagingReady  => 'WSTG';
use constant kImportStatusAnalysisReady => 'WANL';
use constant kImportStatusImportReady   => 'WIMP';

# Running states
#
use constant kImportStatusFetchRun    => 'RFCH';
use constant kImportStatusStagingRun  => 'RSTG';
use constant kImportStatusAnalysisRun => 'RANL';
use constant kImportStatusImportRun   => 'RIMP';

# Error states
#
use constant kImportStatusErrorFetch    => 'EFCH';
use constant kImportStatusErrorStaging  => 'ESTG';
use constant kImportStatusErrorAnalysis => 'EANL';
use constant kImportStatusErrorImport   => 'EIMP';

# The one and only done state...
#
use constant kImportStatusDone => 'DONE';

# Additional error codes
#
use constant kImportStatusError   => 'ERR';
use constant kImportStatusAborted => 'ABRT';

# The following constants will be shared by all the 'staged' metadata tables.
# In other words, all the tables that have 'catalog_import_...' in their names.
# !!! Perhaps these belong in a seperate module?
#
use constant kNew                  => 'NEW';
use constant kUpdate               => 'UPDT';
use constant kReplace              => 'RPLC';
use constant kNewFuture            => 'FUTR';
use constant kUnchanged            => 'SAME';
use constant kDelete               => 'DLT';
use constant kError                => 'ERR';
use constant kErrorBadMatch        => 'ERRM';
use constant kValidationInProgress => 'CHCK';
use constant kNotChecked           => undef;

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

    return $class->GetAll( "SELECT * FROM " . kTable . " ORDER BY catalog_import_id DESC" );
}

sub GetAllInState {
    my ( $class, @states ) = @_;
    assert( scalar @states > 0 );

    my $dbo = Common::RSApp::GetClientDB();
    my @quotedStates;
    foreach my $state (@states) {
        push @quotedStates, $dbo->DBQuote($state);
    }

    return $class->GetAll( "SELECT * FROM " . kTable . " WHERE status IN (" . join( ',', @quotedStates ) . ")" );
}

sub GetLastSuccessfulUpdate {
    my $class = shift;

    my $sql =
      "SELECT * FROM " . kTable . " WHERE status = " . $class->quote(kImportStatusDone) . " ORDER BY import_end_time DESC " . " LIMIT 1";

    Common::Log::Debug("QUERY: $sql");

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

# This method will delete records from the staging tables.
# Not _all_ tables, mind you - just the big ones that hold
# temporary catalog state.
#
sub CleanUp {
    my ( $class, $id ) = @_;

    assert($id);

    my $dbo = Common::RSApp::GetClientDB();
    $dbo->DoCmd("DELETE FROM catalog_import_book_contributor WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_book WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_book_product WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_book_subject WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_contributor WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_discount WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_imprint WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_market WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_product_market WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_product_market_price WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_product WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_region WHERE catalog_import_id=$id");
    $dbo->DoCmd("DELETE FROM catalog_import_supplier WHERE catalog_import_id=$id");
    $dbo->DoCmd(
"DELETE FROM catalog_import_region_excluded_country WHERE catalog_import_region_id NOT IN (select catalog_import_region_id from catalog_import_region)"
    );
    $dbo->DoCmd(
"DELETE FROM catalog_import_region_excluded_territory WHERE catalog_import_region_id NOT IN (select catalog_import_region_id from catalog_import_region)"
    );
    $dbo->DoCmd(
"DELETE FROM catalog_import_region_included_country WHERE catalog_import_region_id NOT IN (select catalog_import_region_id from catalog_import_region)"
    );
    $dbo->DoCmd(
"DELETE FROM catalog_import_region_included_territory WHERE catalog_import_region_id NOT IN (select catalog_import_region_id from catalog_import_region)"
    );
}

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

    my $sql = "SELECT MAX(catalog_import_id) as max_id FROM " . kTable;
    my $sth = $dbo->DoCmd($sql);
    my $hr  = $sth->fetchrow_hashref();
    return $hr->{max_id};
}

1;
