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

use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::FormObject;
use Common::DB::Item::PayeeType;

use lib '/app/tools/rps/lib';
use RPS::ArtistRoyalty::ArtistRoyaltyRun;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::DB::Item::PortalEmailCustomText;
use RPS::Payor::Payor;
use RPS::Portal::Job::SendNotification;
use RPS::RoyaltyRun::Status;
use RPS::Statement::Artist::StatementListWithPayments;

use base 'Common::FormObject';

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

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

    $self->{_sendAll}  = $args{sendAll};
    $self->{_runID}    = $args{runID};
    $self->{_payorID}  = $args{payorID};
    $self->{_filterBy} = $args{filterBy};

    $self->{ArtistRoyaltyStatementList} = RPS::Statement::Artist::StatementListWithPayments->new(
        artistRoyaltyRunID => $args{runID},
        payorID            => $args{payorID},
        filterBy           => $args{filterBy},
        pageSize           => $args{pageSize},
        page               => $args{page}
    );

    $self->{Payor} = RPS::Payor::Payor->new( payorID => $args{payorID} );
    $self->{ArtistRoyaltyRun} = RPS::ArtistRoyalty::ArtistRoyaltyRun->new(
        artistRoyaltyRunID => $args{runID},
        loadSubs           => 0,
    );

    $self->{DistributedCount} = RPS::DB::Item::ArtistRoyaltyStatement->GetDistributedCount(
        runID    => $args{runID},
        payorID  => $args{payorID},
        filterBy => $args{filterBy}
    );

    $self->{EligibleCount} = RPS::DB::Item::ArtistRoyaltyStatement->GetEligibleCount(
        runID    => $args{runID},
        payorID  => $args{payorID},
        filterBy => $args{filterBy}
    );

    $self->{RoyaltyRunStatus} = new RPS::RoyaltyRun::RoyaltyRunStatusList( artist => 1, payorID => $args{payorID} );

    $self->{EmailCustomNotificationText} = RPS::DB::Item::PortalEmailCustomText->GetCustomNotificationText() ? 1 : 0;

    die "ERROR - cannot distribute statements for runs in this state"
      unless ( RPS::RoyaltyRun::Status::kCommitted == $self->{ArtistRoyaltyRun}->Status()
        || RPS::RoyaltyRun::Status::kClosed == $self->{ArtistRoyaltyRun}->Status() );

    return $self;
}

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

    my $clientID = Common::RSApp::GetClientID();
    my $runID    = $self->{_runID};
    my $payorID  = $self->{_payorID};
    my $filterBy = $self->{_filterBy};
    my @payeeIDs;

    my $statementIDParam = $args->{statementID};
    my @statementIDs;

    # Grab all the statement IDs that were select on the current page.
    if ($statementIDParam) {
        if ( ref($statementIDParam) eq 'ARRAY' ) {
            @statementIDs = @$statementIDParam;
        } else {
            $statementIDs[0] = $statementIDParam;
        }
    }

    # See if we need to send invites for the rest of the pages.
    if ( $self->{_sendAll} ) {

        # We already have the statement IDs we need from the current page, so
        # we need to exclude everything on the current page from the bulk update.
        my $currentPage = $self->{ArtistRoyaltyStatementList};

        my %currentStatementIDs;
        foreach my $statement ( @{ $currentPage->{ArtistStatement} } ) {
            $currentStatementIDs{ $statement->ArtistRoyaltyStatementID() } = 1;
        }

        # Now we grab all of the statements.
        my $allPages = RPS::Statement::Artist::StatementListWithPayments->new(
            artistRoyaltyRunID => $runID,
            payorID            => $payorID,
            filterBy           => $filterBy,
        );

        # And now we filter out the ones from the front page.
        foreach my $statement ( @{ $allPages->{ArtistStatement} } ) {
            if ( !$currentStatementIDs{ $statement->ArtistRoyaltyStatementID() } ) {

                # We also need to make sure distribution is set to Online
                # _and_ the statement has not been sent already.
                if ( ( $statement->ArtistPayee->Distribution() == 1 ) && !$statement->DateSent() ) {
                    push( @statementIDs, $statement->ArtistRoyaltyStatementID() );
                }
            }
        }
    }

    foreach my $statementID (@statementIDs) {
        my $statement = RPS::DB::Item::ArtistRoyaltyStatement->Lookup( artist_royalty_statement_id => $statementID );
        $statement->date_sent(Common::DB::Item::kDateTimeNow);
        $statement->save();
        push( @payeeIDs, $statement->payee_id );
    }

    my $payeeList = join( ",", @payeeIDs );

    # Queue a job to send a notification for each statement that was just "distributed" to the portal
    my $jobArgs = RPS::Portal::Job::SendNotification->new(
        payeeType => Common::DB::Item::PayeeType::kPayeeTypeArtist,
        payeeList => $payeeList,
        runID     => $runID,
        clientID  => $clientID,
    );
    my $job = $jobArgs->enqueue();

    # Need to return the final count for the success message.
    my $distributedCount = scalar @statementIDs;

    return $distributedCount;
}


1;
