#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package BookPub::Catalog::Product::Book::WithPricing;

use strict;
use warnings;

use Data::Dumper;

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

use Common::RSApp;
use Common::Log;
use Common::Assert;

use BookPub::Price::ProductMarketPriceList;
use BookPub::DB::Item::Market;
use BookPub::Catalog::Region::RegionWithCountries;
use BookPub::Catalog::Market::MarketWithPricingByCurrency;
use BookPub::Price::DefaultPrice::PrimaryMarket;
use BookPub::Price::DefaultPrice::SecondaryMarket;

use base 'BookPub::Catalog::Product::Book::WithFormat';

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

    # Invoke the inherited method first.
    #
    $self->SUPER::_initProperties($props);

    $self->{Pricing} = $self->_getPricing();

    $self->{DefaultPrimary} = new BookPub::Price::DefaultPrice::PrimaryMarket( productID => $self->ProductID );
    $self->{DefaultSecondary} = new BookPub::Price::DefaultPrice::SecondaryMarket( productID => $self->ProductID );
}

sub _getPricing {
    my $self = shift;
    my @result;
    my $item;

    my $collection = BookPub::DB::Item::Market->GetAllByProductID( $self->ProductID );

    while ( my $row = $collection->next ) {
        $item = BookPub::Catalog::Market::MarketWithPricingByCurrency->new(
            dbItem    => $row,
            marketID  => $row->market_id,
            productID => $self->ProductID
        );

        push( @result, { Market => $item } );
    }

    return \@result;
}

sub getCurrentPrice {
    my ( $self, $marketID, $currencyCode ) = @_;
    assert($marketID);
    assert($currencyCode);

    my $price;

    my $pricingArray = $self->{Pricing};
    foreach my $element (@$pricingArray) {
        my $marketObj = $element->{Market};

        if ( $marketObj->{MarketID} == $marketID ) {
            $price = $marketObj->getCurrentCurrencyPrice($currencyCode);
        }
    }

    return $price;
}

sub getPriceByCurrency {
    my $self = shift;
    my $currencyCode = shift || $self->DefaultPrimary->CurrencyCode();

    my $price;

    my $pricingArray = $self->{Pricing};
    foreach my $element (@$pricingArray) {
        my $marketObj = $element->{Market} || next;
        $price = $marketObj->getCurrentCurrencyPriceObject($currencyCode);

        return $price if ($price);
    }

    return;
}

###
1;    #
###
