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

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::PriceTypeVariance;
use BookPub::Price::Validator;
use Common::RSApp;
use Common::Util;
use Common::Assert;
use Common::FormObject;

use base 'BookPub::Price::PriceType';

sub _initProperties {
    my ( $self, $props ) = @_;

    $self->SUPER::_initProperties($props);

    $self->{AllowedVariance} = $self->_getVariance();

}

sub _propertiesFromDefaults {
    my ( $self, $hrProperties ) = @_;
}

sub _getVariance {
    my $self = shift;
    my $id = $self->PriceTypeID || return;

    my $dbitem = BookPub::DB::Item::PriceTypeVariance->Lookup( price_type_id => $id );

    return $dbitem ? $dbitem->variance : undef;
}

sub save {
    my ($self) = @_;

    my $dbObj;
    if ( defined $self->PriceTypeID() ) {
        $dbObj = BookPub::DB::Item::PriceTypeVariance->Lookup( price_type_id => $self->PriceTypeID() );
    } else {
        $dbObj = BookPub::DB::Item::PriceTypeVariance->Create();
    }

    # set fields here
    #
    $dbObj->variance( $self->AllowedVariance() );

    if ( $dbObj->isDirty() ) {

        # save db item
        #
        $dbObj->save();

        # Summon the validator
        #
        my $validator = BookPub::Price::Validator->new( priceTypeID => $self->PriceTypeID() );

        # Create the jobby job.
        #
        $validator->createJob( tolerance => $self->AllowedVariance() );
    }

    # reload object
    #
    $self->_init( _dbItem => $dbObj );
}

###
1;    #
###
