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

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

use base 'BookPub::RDAS::Form::ProductMonitor::ProductMonitorItem';

sub _getDBItemClass { 'BookPub::DB::Item::ProductMonitorItemPrice' }
sub _objectType     { 'price' }

sub _propertiesFromDB {
    my ( $self, $hrProperties, $id ) = @_;

    my $parent = BookPub::DB::Item::ProductMonitorItem->Lookup( product_monitor_item_id => $id );
    $self->SUPER::_propertiesFromDBItem( $hrProperties, $parent );

    my $dbItem = BookPub::DB::Item::ProductMonitorItemPrice->Lookup( product_monitor_item_id => $id );
    $self->_propertiesFromDBItem( $hrProperties, $dbItem );
}

sub _propertiesFromServiceID {
    my ( $self, $hrProperties, $serviceID, $productID ) = @_;

    assert($serviceID);
    assert($productID);

    my $current = BookPub::DB::Item::ProductMonitorItemPrice->GetCurrent( product_id => $productID, service_id => $serviceID );

    if ($current) {
        $self->_propertiesFromDB( $hrProperties, $current->product_monitor_item_id );
    } else {
        $self->_propertiesFromDefaults($hrProperties);
    }
}

sub _propertiesFromDBItem {
    my ( $self, $hrProperties, $dbItem ) = @_;

    $hrProperties->{price}         = $dbItem->price;
    $hrProperties->{currency_code} = $dbItem->currency_code;
}

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

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

    $self->{Price} = Common::FormObject::Scalar::Money->new( value => $props->{price} );
    $self->{CurrencyCode} = $props->{currency_code};

    return $self;
}

sub create {
    my $self = shift;
    my $data = shift || die "data required";
    my %args = @_;

    my $id = $self->SUPER::create( $data, %args ) || return;

    my $dbItem = BookPub::DB::Item::ProductMonitorItemPrice->Create(
        product_monitor_item_id => $id,
        price                   => $data->{price},
        currency_code           => $data->{currency_code},
    );

    $dbItem->save();

    return $dbItem->product_monitor_item_id;
}

###
1;    #
###
