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

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

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

use lib '/app/tools/rps/lib';
use RPS::Mechanical::UK::McpsLicenseRetention;
use RPS::DB::Item::McpsLicenseRetention;
use RPS::DB::Item::ProductPrice;
use RPS::DB::Item::Price;

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

use constant kMaxEntries => 4;


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

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

	my $mcpsLicenseID = $args{mcps_license_id};
	my $productID = $args{product_id};

    $self->{McpsLicenseRetention} = [];
    
    my @periodTotals;
    my %priceRows;
    
	if($mcpsLicenseID)
	{
        # First we need to know if this license has been used in a committed run. 
        # This affects the way we figure out prices for retentions.
        #
        my $committedRuns = RPS::DB::Item::McpsLicenseRun->NumCommittedRuns($mcpsLicenseID);	    
        
		my $collection = RPS::DB::Item::McpsLicenseRetention->GetByMcpsLicenseID($mcpsLicenseID);

		while ($collection->hasNext())
		{
			my $obj = $collection->next();
				
			$self->{McpsLicenseRetention}->[$obj->period_id-1] = RPS::Mechanical::UK::McpsLicenseRetention->new(_dbItem => $obj);
			
			$periodTotals[$obj->period_id-1] += $obj->units_held;
			   
			
			my $price = 0;
			if ($committedRuns > 0)
			{
			    $price = $obj->price;
			}
			else
			{
	            my $productPrice = RPS::DB::Item::ProductPrice->GetByProductIDPriceLevelID($productID, $obj->price_level_id);
	            if ($productPrice)
	            {
        	        # These are the prices that are currently set for a product.
        	        # These are the ones the template will use if an mcps license has not been
        	        # in a committed run.
        	        #
        	        my $priceID = $productPrice->price_id;
        	        my $priceEntry = RPS::DB::Item::Price->Lookup(price_id => $priceID);
        	        $price = $priceEntry->retail;			    
        		}
			}   			    
			    
			my $periodName = "Period" . $obj->period_id;    
		    $priceRows{$price}{$periodName} += $obj->units_held;
		    $priceRows{$price}{Total} += $obj->units_held;
		}
		
	}

	# fill in the unused periods as place holders
	#
	for(my $i=0; $i < kMaxEntries; $i++)
	{
		if(! defined $self->{McpsLicenseRetention}->[$i])
		{
			$self->{McpsLicenseRetention}->[$i] = RPS::Mechanical::UK::McpsLicenseRetention->new();
		}
	}
	
	my $grandTotal = 0;
	
	for(my $i=0; $i < kMaxEntries; $i++)
	{
	    my $tagName = "McpsLicenseRetentionPeriod" . ($i + 1) . "Total";
	    $grandTotal += $periodTotals[$i];
	    $self->{$tagName} = Common::Client::Current()->Locale()->formatNumber($periodTotals[$i]);   
    }
    
    $self->{McpsLicenseRetentionTotal} = Common::Client::Current()->Locale()->formatNumber($grandTotal);

    my $i = 0;
 	foreach my $price (sort keys %priceRows)
	{
	    $self->{PriceRows}{PriceRow}->[$i]{Price} = Common::Client::Current()->Locale()->formatNumber($price, '.2');

	    my $priceRowRef = $priceRows{$price}; 
	    my %priceRow = %$priceRowRef;
	    
     	foreach my $tag (sort keys %priceRow)
    	{
    	    $self->{PriceRows}{PriceRow}->[$i]{$tag} = $priceRow{$tag};
    	}
	    
	    $i++;
    }   

    return $self;
}




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



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

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

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

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


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

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

	foreach my $retention (@{$self->{McpsLicenseRetention}})
	{
		if(! $retention->validate())
		{
			$self->setError(Common::FormObject::kErrFieldInvalid);
			$valid = 0;
		}

	}


	return $valid;
}


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

	foreach my $retention (@{$self->{McpsLicenseRetention}})
	{
	    if ($retention->Delete)
	    {
	        $retention->delete;
	    }
	    else
	    {
            $retention->save();
        }
	}
}


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

	return $self->{McpsLicenseRetention};
}


1;



