#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Track::Command::PreSubmit;
use strict;
use warnings;

use lib '/app/tools/rps/lib';
use RPS::Master::Master;
use RPS::DB::Item::Master;
use RPS::Song::Song;
use RPS::DB::Item::Song;

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

use RPS::XMLCommand;
use base 'RPS::XMLCommand';

sub cmd  { return 'presubmit'; }
sub area { return 'track'; }

use constant kTemplate => '/app/tools/rps/templates/track/index.xsl';

sub execute {
    my ($self) = @_;

    my $response = $self->SUPER::execute();
    return $response if $response;

    $self->checkForDuplicateMaster();
    $self->checkForDuplicateSong();

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

    return $response;
}

# ------------------------------------------
# Help functions to check for duplicates
# ------------------------------------------

sub checkForDuplicateSong {
    my ($self) = @_;

    my $newISWC = $self->getParam("SongISWC");
    return 0 if ( !$newISWC );

    my $dupsFound = 0;
    if ( !$self->getParam("SongID") ) {
        my $songs = RPS::DB::Item::Song->Match($newISWC);
        if ( defined $songs && $songs->hasNext() ) {
            my $data = $songs->next();
            push @{ $self->{xml}{DuplicateSongs} }, new RPS::Song::Song( _dbItem => $data );
            $dupsFound++;
        }
    }

    return $dupsFound;
}

sub checkForDuplicateMaster {
    my ($self) = @_;

    my $newISRC = $self->getParam("MasterISRC");
    return 0 if ( !$newISRC );

    my $dupsFound = 0;
    if ( !$self->getParam("MasterID") ) {
        my $masters = RPS::DB::Item::Master->Match($newISRC);
        if ( defined $masters && $masters->hasNext() ) {
            my $data = $masters->next();
            push @{ $self->{xml}{DuplicateMasters} }, new RPS::Master::Master( _dbItem => $data );
            $dupsFound++;
        }
    }

    return $dupsFound;
}

###
1;    # Play nicely.
###
