#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package BookPub::Tracker::Command::ReopenFile;
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 "reopen"; }
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 $fileID = $self->getParam('file');
    die "ERROR - no file id specified" unless defined $fileID;

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

    my $file = BookPub::Tracker::File->new( fileID => $fileID );

    # We have no business here if the file is not closed...
    #
    die "ERROR - Cannot re-open a non-closed file" unless ( BookPub::DB::Item::File::STATUS_CLOSED == $file->FileStatus() );
    die "ERROR - Cannot re-open a closed file that is not in period 0" unless ( 0 == $file->PeriodID() );

    # Let's use an exception model here.
    # !!! For now we'll just return a generic error, but we can extend this
    # by using an Exception class.
    #
    eval { $file->reopen(); };

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

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

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

1;
