#------------------------------------------------------------
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Tracker::Command::DeleteFile;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;
use RSApache::Response::Download;
use Common::Assert;
use RSApache::Message;

use lib '/app/tools/bookpub/lib';
use BookPub::Tracker::File;
use BookPub::Tracker::Command::Main;

use base 'BookPub::Command';

sub cmd      { return "delete"; }
sub area     { return "tracker"; }
sub pageName { return 'Revenue File Delete'; }

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 $fileID;

    my $file = BookPub::Tracker::File->new( fileID => $fileID );
    die "Error - unable to instantiate File with id $fileID" unless $file;

    my $page = $self->getParam('page');

    my $origFileName = $file->OrigFileName;

    my $message;
    eval { $file->delete(); };

    if ($@) {

        # If this was an ErrorMessage exception, add the message to the redirect.
        # Otherwise, re-throw it.
        #
        if ( ref $@ && $@->isa('RSApache::Message') ) {
            $message = $@;
        } else {
            die $@;
        }
    }

    # No matter what happened, we'll redirect back to the page that the file
    # was deleted from.
    #
    if ( !$message ) {
        $message = RSApache::Message->new( type => 'success', code => 'file_deleted' );
    }

    my %newParams = (
        msg  => $message->toString(),
        page => $page,
    );

    my $command = BookPub::Tracker::Command::Main->new(%newParams);
    return RSApache::Response::Redirect->new( $command->getRedirect() );
}

1;
