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

use Carp;
use strict;
use warnings;

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

use lib '/app/tools/rps/lib';
use RPS::Finance::Account;
use RPS::DB::Item::FinanceAccount;

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


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

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

    my %properties;

    $properties{$self->_licenseID()} = $args{trackLicenseID};

    $self->_initProperties(\%properties);
    $self->_initSubs(\%properties);

    return $self;
}


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

    $self->{TrackLicenseID}		= Common::FormObject::Scalar->new(value => $props->{$self->_licenseID()}, readOnly => 1);
}


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

	if($self->loadSubs())
	{
        my $trackLicense = $self->_license()->Lookup($self->_licenseID() => $props->{$self->_licenseID()});
        my $accountID = $trackLicense->finance_account_id;

		if($accountID)
		{
        	$self->{FinanceAccount} = RPS::Finance::Account->new(accountID => $accountID);
		}
        else
        {
        	$self->{FinanceAccount} = RPS::Finance::Account->new();

            $self->{FinanceAccount}->CurrencyCode($self->_currencyCode());
        }
	}
}


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

    my $trackLicenseID= $self->TrackLicenseID();
    assert($trackLicenseID);

    if (! $self->{FinanceAccount}->Description())
    {
        $self->{FinanceAccount}->Description("account for track license $trackLicenseID");
    }
    if (! $self->{FinanceAccount}->TypeCode())
    {
        $self->{FinanceAccount}->TypeCode(RPS::DB::Item::FinanceAccount::kAccountTypeHoldover);
    }
    $self->{FinanceAccount}->save();
    my $accountID = $self->{FinanceAccount}->AccountID();

    my $trackLicense = $self->_license()->Lookup($self->_licenseID() => $trackLicenseID);
    if ($trackLicense->finance_account_id)
    {
        assert($trackLicense->finance_account_id == $accountID, "ERROR - new finance account $accountID created, but track license $trackLicenseID already has an account!");
    }
    else
    {
        $trackLicense->finance_account_id($accountID);
        $trackLicense->save();
    }

    return 1;
}





###
1;#
###


