#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package Sale::Price::Validator;
use strict;
use warnings;

use lib '/app/tools/common/lib';

use Common::RSApp;
use Common::Util;
use Common::Assert;
use Common::ClientSettings::Service;

use Data::Dumper;

sub new {
    my $class = shift;
    my $self = bless {}, $class;

    $self->_init(@_);

    return $self;
}

# When we destroy the object we want to update the validation counts in the file
# table
sub DESTROY {
    my $self = shift;

    # Let's just update the validation counts every time.
    # This doesn't take very long and it's not always happening when it should.

    #if( $self->{_isDirty} ) {
    #    Common::Log::Debug( "-- Updating Validation Counts" );
    $self->_updateValidationCounts();

    #}
}

sub _init {
    my ( $self, %args ) = @_;

    $self->{_saleID}      = $args{saleID};
    $self->{_fileID}      = $args{fileID};
    $self->{_priceTypeID} = $args{priceTypeID};

    return $self;
}

sub run {
    my $self = shift;

    my $collection = $self->_getRecordsToValidate();

    while ( my $row = $collection->next ) {
        $self->_validatePrice($row);

        # Mark the sale as examined
        $row->date_price_validated(Common::DB::Item::kDateTimeNow);
        $row->save;
    }
}

sub createJob {
    my $self = shift;
    my %args = @_;

    Common::Log::Debug("Creating new validation job");
    my $job = $self->_validationJobObject(%args);

    $job->enqueue();
}

sub clear {
    my $self = shift;
    my %args = @_;

    if ( $self->_canValidatePrice() ) {
        $self->{_isDirty} = 1;
        $self->_clearValidation(%args);
    }
}

sub _canValidatePrice {
    Common::Client::Current()->isClientType(Common::Client::kSalePriceValidation);
}

sub _getRecordsToValidate   { assert( undef, "Must be overloaded" ) }
sub _getTolerance           { assert( undef, "Must be overloaded" ) }
sub _getStoredPrice         { assert( undef, "Must be overloaded" ) }
sub _getSalePrice           { assert( undef, "Must be overloaded" ) }
sub _checkForAutoException  { assert( undef, "Must be overloaded" ) }
sub _createException        { assert( undef, "Must be overloaded" ) }
sub _clearValidation        { assert( undef, "Must be overloaded" ) }
sub _autoMatchRule          { assert( undef, "Must be overloaded" ) }
sub _validationJobObject    { assert( undef, "Must be overloaded" ) }
sub _updateValidationCounts { assert( undef, "Must be overloaded" ) }
sub _isFree                 { assert( undef, "Must be overloaded" ) }
sub _getUnits               { assert( undef, "Must be overloaded" ) }

sub _validatePrice {
    my $self   = shift;
    my $dbItem = shift;
    my $minDelta;
    my $deltaPrice;
    my $priceValid;

    # Check to ensure we can validate the sale.
    return unless ( $self->_shouldValidate($dbItem) );

    Common::Log::Debug( "Validating Price for Sale ID: " . $dbItem->sale_id );

    my ( $catalogPrices, $salePrice, $tolerance ) = $self->_getValidationData($dbItem);

    ###
    #   Iterate through each price and store the price closest to the reported list price
    ###

    if ( $catalogPrices && $salePrice && $tolerance ) {

        # Flag that we have modified something

        foreach my $priceObj (@$catalogPrices) {
            my $price = $self->_priceFromObj($priceObj);

            if ( $price == 0 || $salePrice == 0 ) {

                # Need to handle this separately to avoid weirdness with zeroes.
                if ( $salePrice == $price ) {
                    $priceValid = 1;
                    last;
                } else {
                    $deltaPrice = $priceObj;
                }
            } else {
                my $delta = abs( 1 - ( $salePrice / $price ) ) * 100;
                Common::Log::Debug( "Test price variance: abs( 1 - ( $salePrice / $price ) ) * 100 = $delta " . "Tolerance: $tolerance " );

                if ( $delta <= $tolerance ) {
                    $priceValid = 1;
                    last;
                } else {
                    if ( !$minDelta || $delta < $minDelta ) {
                        $deltaPrice = $priceObj;
                        $minDelta   = $delta;
                    }
                }
            }
        }
    }

    # Some sales (like those for out of print products) should always create exceptions.
    my $autoException = $self->_checkForAutoException($dbItem);

    ###
    #   Create an exception
    ###
    if (!$priceValid || $autoException) {
        my $approved = 0;

        if ( !$autoException ) {
            $approved = $self->_autoMatchRule($dbItem);
        }

        Common::Log::Debug( sprintf( " -- Checking for rule match: %s ", $approved ? "APPROVED!" : "no match" ) );
        $self->_createException(
            saleID   => $dbItem->sale_id,
            price    => $deltaPrice,
            variance => $minDelta,
            approved => $approved
        );
    }

}

sub _priceFromObj {
    my $self = shift;
    return shift->Price;
}

sub _getValidationData {
    my $self = shift;
    my $sale = shift || die;

    # If we are getting validation data that means we are validating and must
    # refresh the counts when we are done.
    $self->{_isDirty} = 1;

    my $salePrice = $self->_getSalePrice($sale);
    my $tolerance = $self->_getTolerance($sale);

    ###
    #    Validate that we have enough data to do price validation
    ###
    unless ( $sale->price_type_id ) {
        Common::Log::Debug( "WARNING: Not validating. No price type found in sale id: " . $sale->sale_id );
        return;
    }

    unless ($tolerance) {
        Common::Log::Debug( "WARNING: Not validating. No price tolerance found for price type id: " . $sale->price_type_id );
        return;
    }

    # _getStoredPrice can return a scalar or an array.
    my $storedPrice = $self->_getStoredPrice($sale);
    my @prices = ref($storedPrice) ? @$storedPrice : ($storedPrice);

    unless (@prices) {
        Common::Log::Print( "WARNING: Not validating. No stored price(s) found for product id: " . $sale->product_id );
        return;
    }

    unless ($salePrice) {
        Common::Log::Print( "WARNING: Not validating. No sale price in sale id: " . $sale->sale_id );
        return;
    }

    return ( \@prices, $salePrice, $tolerance );
}

sub _shouldValidate {
    my $self = shift;
    my $sale = shift || die;

    # First check to see if we should be doing validation
    unless ( $self->_canValidatePrice() ) {
        Common::Log::Debug("WARNING: Client does not seem to have price validation enabled.  Not validating price");
        return;
    }

    # No price validation on free records.
    if ( $self->_isFree($sale) ) {
        Common::Log::Debug( "WARNING: Sale ID: " . $sale->sale_id . " is identified as free.  Not validating price" );
        return;
    }

    # No units
    unless ( $self->_getUnits($sale) ) {
        Common::Log::Debug( "WARNING: Sale ID: " . $sale->sale_id . " has not units.  Not validating price" );
        return;
    }

    unless ( $self->_canServiceValidate( $sale->service_id ) ) {
        Common::Log::Debug(
            "WARNING: Sale ID: " . $sale->sale_id . " service (" . $sale->service_id . ") not set to validate for this client" );
        return;
    }

    return 1;
}

sub _canServiceValidate {
    my $self      = shift;
    my $serviceID = shift || return;
    my $services  = $self->{_clientServiceValidation} ? $self->{_clientServiceValidation} : {};

    unless ( exists( $services->{$serviceID} ) ) {
        my $settings = Common::ClientSettings::Service->new( serviceID => $serviceID );
        $services->{$serviceID} = $settings->ValidatePrice() ? 1 : 0;
        $self->{_clientServiceValidation} = $services;
    }

    return $services->{$serviceID};
}

###
1;    #
###
