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

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

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

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

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

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

sub cmd  { return "unmatch"; }
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 $map_id = $sale->MapID;

    if ( $sale->CanUnmatch( map_id => $map_id ) ) {

        ## find what sales uses this map
        my $sale_records = $sale->GetSalesToUnmatch();

        ## do it on current sale (has to be here, or else won't be updated
        ## through the rest of this script.
        $sale->Unmatch();
        $file->UpdateRemainingExceptions('unmatch');

        ## do it on all other sales
        while ( my ( $sale_id, $file_id ) = each %$sale_records ) {
            next if ( $sale_id == $sale->SaleID );    ## skip over self; already done

            my $temp_sale = RPS::File::Sale->new( sale_id => $sale_id );
            $temp_sale->Unmatch();

            my $temp_file = RPS::File::File->new( file_id => $file_id );
            $temp_file->UpdateRemainingExceptions('unmatch');
        }

        ## delte the map
        my $clientID = Common::RSApp::GetClientID();
        my $sm = new RPS::Sale::Match( client_id => $clientID );
        $sm->RemoveMatch( map_id => $map_id );

    } else {
        $self->addMessageXML( type => "error", code => "unmatch_failed" );
    }

    $response = $self->showMatchOptions( $sale, $file );
    return $response if $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;
