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

use strict;
use warnings;

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

use lib '/app/tools/rps/lib';
use RPS::Payor::Payor;
use RPS::DB::Item::PublisherIndirectBalanceAccount;

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

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

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

	my $publisherID = $args{publisherID};
	my $payorID = $args{payorID};
	
	unless ($publisherID && $payorID)
    {
        assert(0, 'publisher and payor are required');
    }	
    
    my $publisher = $self->_publisherObj()->new(
        publisherID => $publisherID,
        loadSubs => 0,
        readOnly => 1,
    );    

    my $indirectPublisherID;
    my $agentID = $publisher->AgentID();
    my $adminID = $publisher->AdminID();
    
    if ($agentID)
    {
        $indirectPublisherID = $agentID;
    }
    else
    {
        $indirectPublisherID = $adminID;
    }

    # There may not be an account yet, so we need to do create one (but only if there is an admin or agent).
    #
    my $currentAccount;
    my $currentAccountID;
    if ($indirectPublisherID)
    {
        $currentAccount = $self->_publisherAccount()->new(payorID => $payorID, publisherID => $publisherID, indirectPublisherID => $indirectPublisherID);
        $currentAccountID = $currentAccount->FinanceAccountID();
    }

    # Grab all of the accounts associated with this publisher/payor combo
    #
    $self->{AccountList} = $self->_accountList()->new(payorID => $payorID, publisherID => $publisherID, currentAccountID => $currentAccountID);
    
    # Add the current account to the list, if there is one.
    #
    if ($currentAccount)
    {
        push @{$self->{AccountList}{Account}}, $currentAccount;   
    }

    $self->{Publisher} = $publisher;

    $self->{Payor} = RPS::Payor::Payor->new(
        payorID => $payorID,
        loadSubs => 0,
        readOnly => 1,
    );   
    
    my $indirectLicenses = $self->_trackLicense()->GetIndirectByPublisherIDPayorID($publisherID, $payorID);
    $self->{Payor}->{PublisherIndirectLicenseCount} = $indirectLicenses->size(); 

    my $totalLicenses = $self->_trackLicense()->GetByPublisherIDPayorID($publisherID, $payorID);
    $self->{Payor}->{PublisherTotalLicenseCount} = $totalLicenses->size();    
    
    $self->{RoyaltyRunStatus} = $self->_royaltyRunStatusList();   

	return $self;
}


sub save
{
	my ($self) = @_;
	
    $self->{AccountList}->save(); 
    
}


sub publisherID
{
	my ($self) = @_;
	return $self->{Publisher}->PublisherID();
}

###
1;#
###
