#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::ArtistRoyalty::Command::Show;
use strict;
use warnings;

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

use lib '/app/tools/rps/lib';
use RPS::ArtistRoyalty::ArtistRoyaltyRun;
use RPS::Command;
use RPS::DB::Item::ClientOptions;
use RPS::Payor::Payor;
use base 'RPS::Command';

use RSApache::Response::XSLT;
use RSApache::Response::XSLTDownload;

sub area { return 'artist_royalty'; }
sub cmd  { return 'show'; }

use constant kTemplate     => "/app/tools/rps/templates/artist_royalty/index.xsl";
use constant kTextTemplate => "/app/tools/rps/templates/artist_royalty/text/index.xsl";

use constant MAX_PAGE_SIZE => 1_000_000_000;
use constant STICKY_PREFIX => 'pe_' . __PACKAGE__->area() . '_';
use constant STICKY_PARAMS => {
    pageSize => 100,
};

sub _maxPageSize       { MAX_PAGE_SIZE }
sub _stickyParamPrefix { STICKY_PREFIX }
sub _stickyParams      { STICKY_PARAMS }

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

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

    my $hParams  = $self->_preprocessStickyParams( $self->_stickyParamPrefix, $self->_stickyParams );
    my $runID    = $hParams->{RoyaltyRunID};
    my $payorID  = $hParams->{PayorID};
    my $filterBy = $hParams->{filterBy};
    my $download = $hParams->{download};
    my $page     = $hParams->{page} || 1;
    my $pageSize = $hParams->{pageSize};

    $pageSize = $self->_maxPageSize if $download || $pageSize eq 'all';

    $self->{xml}{CustomReport} = RPS::DB::Item::ClientOptions->Get('custom_statement_summary');
    $self->{xml}{RoyaltyBreakdown} = RPS::DB::Item::ClientOptions->Get('royalty_breakdown');

    my $artistRun = RPS::ArtistRoyalty::ArtistRoyaltyRun->new(
        artistRoyaltyRunID => $runID,
        payorID            => $payorID,
        filterBy           => $filterBy,
        page               => $page,
        pageSize           => $pageSize,
    );

    $self->{xml}{ArtistRoyaltyRun} = $artistRun;

    # I want to be able to link to this page without passing in a payor id...
    #
    if ( !$payorID ) {
        $payorID = $artistRun->PayorID();
    }

    my $payor = RPS::Payor::Payor->new( payorID => $payorID );
    $self->{xml}{Payor} = $payor;

    if ($download) {
        my $cleanRunLabel = Common::Util::clean_name( $self->{xml}{ArtistRoyaltyRun}->Label() );

        my $filename = "Summary_$cleanRunLabel.txt";
        $response = RSApache::Response::XSLTDownload->new( $self->{xml}, kTextTemplate, $filename );
    } else {
        $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
    }
    return $response;
}


1;
