package RPS::Publisher::Command::US::Delete;

use lib '/app/tools/rps/lib';
use RPS::CommandLog;

use lib '/app/tools/common/lib';
use Common::FormObject;
use RSApache::Response::XML;
use RSApache::Response::XSLT;
use RSApache::Response::Redirect;

use RPS::Payee::Command::Main;
use RPS::Publisher::Command::US::Edit;
use RPS::RoyaltyRun::RoyaltyRunStatusList;
use RPS::DB::Item::Publisher;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::PublisherAccount;
use RPS::DB::Item::FinanceTransaction;

use parent 'RPS::Command';


use constant kTemplate => '/app/tools/rps/templates/publisher/edit.xsl';

sub cmd  { 'delete' }
sub area { 'publisher' }

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

    my $response = $self->SUPER::execute();
    return $response if $response;

    my $id = $self->getParam('PublisherID') || 0;
    unless ( $id && $id =~ /^\d+$/ ) {
        return $self->_redirectToPayeeForm();
    }

    if ( my $oPublisher = RPS::DB::Item::Publisher->Lookup( publisher_id => $id ) ) {
        if ( $self->_isActionAllowed($oPublisher) ) {
            $oPublisher->delete();
            return $self->_redirectToPayeeForm('success');
        } else {
            return $self->_redirectToEditForm('error', $id);
        }
    }

    return $self->_redirectToPayeeForm();
}

sub _isActionAllowed {
    my ($self, $oPublisher) = @_;

    my $restricted = 0;
    $restricted += $self->_isAdminOrAgent($oPublisher);
    $restricted += $self->_hasAttachedLicenses($oPublisher);
    $restricted += $self->_hasRunActivity($oPublisher);
    $restricted += $self->_areActiveRoyaltyRuns();
    $restricted += $self->_hasPendingOrHistoryTransactions($oPublisher);
    $restricted += $self->_hasPublisherItems($oPublisher);

    return !$restricted;
}

sub _isAdminOrAgent {
    my ($self, $oPublisher) = @_;

    my $res = 0;

    my $oCollection = RPS::DB::Item::Publisher->GetByAdminID( $oPublisher->publisher_id );
    while ( my $oItem = $oCollection->next() ) {
        $res += $oItem->publisher_id;
        last;
    }

    $oCollection = RPS::DB::Item::Publisher->GetByAgentID( $oPublisher->publisher_id );
    while ( my $oItem = $oCollection->next() ) {
        $res += $oItem->publisher_id;
        last;
    }

    return $res;
}

sub _hasAttachedLicenses {
    my ($self, $oPublisher) = @_;

    my $res = 0;

    my $oCollection = RPS::DB::Item::Publisher->GetAllWithLicenses( $oPublisher->publisher_id );
    while ( my $oItem = $oCollection->next() ) {
        $res += $oItem->publisher_id;
        last;
    }

    return $res;
}

sub _hasRunActivity {
    my ($self, $oPublisher) = @_;

    # check for any run activity
    return RPS::DB::Item::Publisher->HasRunActivity( $oPublisher->publisher_id );
}

sub _redirectToEditForm {
    my ($self, $status, $id) = @_;

    my %showParams;
    if ( $status && $status =~ /^error/ ) {
        my $oSuccessMessage = RPS::Message->new( type => "error", code => Common::FormObject::kErrFormSubmit );
        %showParams = ( msg => $oSuccessMessage->toString() );
    }

    $showParams{PublisherID} = $id;
    my $oCommand = RPS::Publisher::Command::US::Edit->new( %showParams );
    return RSApache::Response::Redirect->new( $oCommand->getRedirect() );
}

sub _redirectToPayeeForm {
    my ($self, $status) = @_;

    my %showParams;
    if ( $status && $status =~ /^success$/ ) {
        my $oSuccessMessage = RPS::Message->new( type => $status, code => Common::FormObject::kSuccessDelete );
        %showParams = ( msg => $oSuccessMessage->toString() );
    }

    $showParams{payeeType}  = 'publisher';
    $showParams{viewByType} = 'publisher';
    my $oCommand = RPS::Payee::Command::Main->new( %showParams );
    return RSApache::Response::Redirect->new( $oCommand->getRedirect() );
}

sub _areActiveRoyaltyRuns {
    my $self = shift;

    my $hData = RPS::RoyaltyRun::RoyaltyRunStatusList->new( usMechanical => 1 );
    return !$hData->{CanEdit};
}

sub _hasPendingOrHistoryTransactions {
    my ($self, $oPublisher) = @_;

    my $res = 0;

    # pending
    my $oCollection = RPS::DB::Item::PublisherAccount->GetAllWithPendingTransactions(
        undef, $oPublisher->publisher_id
    );
    while ( my $oItem = $oCollection->next() ) {
        $res += $oItem->finance_account_id;
        last;
    }

    # history
    $oCollection = RPS::DB::Item::FinanceTransaction->GetTransactionsHistoryByPublisher( $oPublisher->publisher_id );
    while ( my $oItem = $oCollection->next() ) {
        $res += $oItem->finance_account_id;
        last;
    }

    return $res;
}

sub _hasPublisherItems {
    my ($self, $oPublisher) = @_;

    return RPS::DB::Item::Publisher->IsNotManual($oPublisher->publisher_id)
}


1;
