#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Product::PriceList;

use strict;
use warnings;
use Data::Dumper;
use Carp;

use lib '/app/tools/common/lib';
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::Product::Price;
use RPS::DB::Item::ProductPrice;
use RPS::DB::Item::PriceLevel;

use Common::FormObject;
use base 'Common::FormObject';

sub _listProperties {
    return { Price => 1 };
}

# It really does seem that the easiest way to make this all work will be
# Otherwise, really, it gets amazingly complex.

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

    $self->SUPER::_init(%args);

    my $productID = $args{productID};

    $self->{Price} = [];

    # let's get all the existing product prices
    #
    my %productPrices = ();
    if ($productID) {
        my $collection = RPS::DB::Item::ProductPrice->GetByProductID($productID);

        while ( $collection->hasNext() ) {
            my $obj = $collection->next();
            $productPrices{ $obj->price_level_id } = $obj;
        }
    }

    # Now loop through the price levels.  If we have a price set
    # for this level then use it, otherwise use a placeholder.
    #
    my $priceLevels = RPS::DB::Item::PriceLevel->GetAll();
    while ( $priceLevels->hasNext() ) {
        my $level = $priceLevels->next();

        my $priceObj;
        if ( $productPrices{ $level->price_level_id() } ) {
            $priceObj = RPS::Product::Price->new( _dbItem => $productPrices{ $level->price_level_id() } );
        } else {
            $priceObj = RPS::Product::Price->new();
            $priceObj->ProductID($productID);
            $priceObj->PriceLevelID( $level->price_level_id() );
        }

        push @{ $self->{Price} }, $priceObj;
    }

    return $self;
}

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

    my $valid = $self->SUPER::validate();

    foreach my $price ( @{ $self->{Price} } ) {
        if ( !$price->validate() ) {
            $valid = 0;
        }
    }
    return $valid;
}

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

    foreach my $price ( @{ $self->{Price} } ) {
        $price->save();
    }
}

# This is the special sort of list accessor.
#
sub Price {
    my ( $self, $index, $methodAddressList, $newValue ) = @_;

    if ( 0 == scalar @$methodAddressList ) {
        if ( defined $newValue ) {
            $self->{Price}[$index] = $newValue;
        }
        return 1;
    }

    # May need to dynamically add objects to the list...
    #
    if ( !defined $self->{Price}[$index] ) {
        $self->{Price}[$index] = RPS::Product::Price->new();
    }

    return $self->{Price}[$index]->_accessProperty( $methodAddressList, $newValue );
}

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

    return $self->{Price};
}

###
1;    #
###

