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

use strict;
use warnings;

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

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ReserveLiquidation;
use RPS::License::ReserveLiquidation;

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

use constant kMaxEntries => 8;

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

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

    my $id   = $args{id};
    my $type = $args{type};
    assert($type);

    $self->{ReserveLiquidation} = [];
    if ($id) {
        my $collection = RPS::DB::Item::ReserveLiquidation->GetByIDType( $id, $type );

        while ( $collection->hasNext() ) {
            my $obj = $collection->next();
            $self->{ReserveLiquidation}->[ $obj->period - 1 ] = RPS::License::ReserveLiquidation->new( _dbItem => $obj );
        }
    }

    # fill in the unused periods as place holders
    #
    for ( my $i = 0 ; $i < kMaxEntries ; $i++ ) {
        if ( !defined $self->{ReserveLiquidation}->[$i] ) {
            $self->{ReserveLiquidation}->[$i] = RPS::License::ReserveLiquidation->new();
        }

        # set Type now so we can validate later on
        #
        $self->{ReserveLiquidation}->[$i]->Type($type);
    }

    return $self;
}

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

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

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

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

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

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

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

    my $sum = 0;
    foreach my $liq ( @{ $self->{ReserveLiquidation} } ) {
        if ( !$liq->validate() ) {
            $self->setError(Common::FormObject::kErrFieldInvalid);
            $valid = 0;
        } elsif ( $liq->Percent() ) {
            $sum += $liq->Percent();
        }
    }

    if ( $sum > 0 && $sum != 100 ) {
        $self->setError(Common::FormObject::kErrFieldInvalid);
        $valid = 0;
    }

    return $valid;
}

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

    foreach my $reserveLiq ( @{ $self->{ReserveLiquidation} } ) {
        $reserveLiq->save();
    }
}

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

    return $self->{ReserveLiquidation};
}

1;

