#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package BookPub::Tracker::Command::QwikClose;
use strict;
use warnings;

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

use BookPub::Tracker::File;
use BookPub::Tracker::Command::Main;

use base 'BookPub::Command';

sub cmd      { return "qwikclose"; }
sub area     { return "tracker"; }
sub pageName { return 'Revenue File Tracker'; }

use constant kTemplate => '/app/tools/bookpub/templates/tracker/main.xsl';

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

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $fileIDs = $self->getParam('file');
    die "ERROR - no file ids specified" unless defined $fileIDs;

    if ( 'ARRAY' ne ref($fileIDs) ) {
        my @fileArray = ($fileIDs);
        $fileIDs = \@fileArray;
    }

    # We're going to want to end up on the main page again no matter what.
    #
    my $newCmd = BookPub::Tracker::Command::Main->new();

    eval {
        # We'll loop through the files twice:  Once to validate the files (at least to
        # make sure they have revenue), and once to actually finish
        #
        # I want to do this in two seperate loops, because I don't want to close ANY of the
        # files if any of them are wacked.
        #
        my @files;
        foreach my $fileID (@$fileIDs) {
            my $file = BookPub::Tracker::File->new( fileID => $fileID );

            die "ERROR - Cannot finish a closed file" if ( BookPub::DB::Item::File::STATUS_CLOSED == $file->FileStatus() );
            die "ERROR - File has no revenue" if ( !$file->Revenue );
            die "ERROR - File needs a conversion rate"
              if ( $file->CurrencyCode ne Common::Client::Current()->Locale()->currencyFormat()->currencyCode()
                && ( !$file->InputConversionRate || !$file->conversionRatesAreSet() ) );

            push @files, $file;
        }

        foreach my $file (@files) {
            $file->finishImport();
        }
    };

    if ($@) {
        Common::Log::Print("BookPub::Tracker::Command::QwikClose failed : $@");

        $newCmd->addMessageXML( type => "error", code => "finish_failed" );
    }

    $response = $newCmd->execute();
    return $response;
}

1;
