#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Raptor::Matcher::Command::Match;
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 "match"; }
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 $saleParam = $self->getParam('sale');
    assert($saleParam);

    my $sale = RPS::File::Sale->new( sale_id => $saleParam );
    assert($sale);

    my $file = RPS::File::File->new( file_id => $sale->FileID );
    assert($file);

    my $productParam = $self->getParam('product');
    assert($productParam);

    my $pageParam = $self->getParam('trackerPage');

    my $success = $sale->MakeMatch( $productParam, $file->ServiceID );
    if ( !$success ) {
        $self->addMessageXML( type => 'error', code => 'match_failed' );
    } else {
        $file->UpdateRemainingExceptions();

        my $nextSaleID = $sale->GetNextUnfixedID() || $sale->GetPreviousUnfixedID();
        if ($nextSaleID) {

            # redirect
            return RSApache::Response::Redirect->new("/app/matcher?sale=$nextSaleID&trackerPage=$pageParam");
        }

        $file->RecalculateRemainingExceptions();
    }

    # showMatchOptions _might_ wish to redirect... so we need to see if it returns
    # a response object.
    #
    $response = $self->showMatchOptions( $sale, $file );
    if ($response) {
        return $response;
    }

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

    $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );

    return $response;
}

1;
