#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Raptor::Matcher::Command::File;
use strict;
use warnings;

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

use lib '/app/tools/rps/lib';
use RPS::File::File;
use RPS::File::Sale;

use lib '/app/tools/raptor/lib';
use Raptor::Matcher::Command::Base;

use Raptor::Command;
use base 'Raptor::Matcher::Command::Base';

sub cmd  { return "file"; }
sub area { return "matcher"; }

use constant kTemplate => '/app/tools/raptor/templates/matcher.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 $fileParam = $self->getParam('file');

    # The page param is just used to return users to the correct tracker page
    # once they are done matching.
    my $pageParam = $self->getParam('page');

    if ( my $lineNum = $self->getParam('line') ) {
        my $file = RPS::File::File->new( file_id => $fileParam );
        $self->{xml}{File} = $file->GetObjectXML();

        my $sale = RPS::File::Sale->new();
        if ( !$sale->GetByLineNumber( file_id => $fileParam, line_num => $lineNum ) ) {

            # Throw an exception?
            #
            #die "Error - no match for file_id $fileParam, line_num $lineNum";
            #
            # No, it's too easy for a user to accidentally get to this.
            # Let's return the basic XML and let the template throw up an error message.
            $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
        } else {
            $self->setNavLinks($sale);

            $self->{xml}{Sale} = $sale->GetObjectXML();

            # This method _might_ return a redirect...
            #
            $response = $self->showMatchOptions( $sale, $file, search_only => 1 );

            if ( !$response ) {
                $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
            }
        }
    } else {
        my $saleID = RPS::File::Sale->GetFirstSaleError( file_id => $fileParam );
        if ( !$saleID ) {
            $saleID = RPS::File::Sale->GetFirstException( file_id => $fileParam );
        }
        if ($saleID) {
            $response = RSApache::Response::Redirect->new("/app/matcher?c=sale&sale=$saleID&trackerPage=$pageParam");
        } else {
            $response = RSApache::Response::Redirect->new("/app/tracker");
        }
    }

    return $response;
}

1;
