###################################################################
# Copyright (C) 2006 RoyaltyShare, Inc.  All Rights Reserved
###################################################################

package MediaServe::Matcher;

use strict;
use warnings;

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

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::RSDB;
use Common::RSApp;

use lib '/app/tools/mediaserve/lib';
use MediaServe::DB::Item::AlbumFile;

use base 'Common::XMLObject';

sub _init {
    my $self = shift;

    eval "require " . $self->asset_db_class();
    die $@ if $@;

    return $self;
}

sub match_files {
    my ( $self, $type ) = @_;
    my $count = 0;
    my $file;
    my ( $id, $id2 );
    my $id_field = $self->id_field();
    my $class    = $self->asset_db_class();
    my $files    = $class->GetUnmatchedFiles();

    while ( $files->hasNext ) {
        $file = $files->next;

        use Data::Dumper;
        Common::Log::Debug( Dumper($file) );

        Common::Log::Debug( "   Matching file: " . $file->{filename} );

        ( $id, $id2 ) = $class->GetMatchIDs( $self->get_match_criteria( $file->{filename} ) );

        if ($id2) {
            Log->notice( "  Failed match $file->{filename} because multiple matches found, Client: "
                  . Common::RSDB::ClientIDToDBName( Common::RSApp::GetClientID() ) );
        } elsif ($id) {
            $self->remove_duplicate_assets( $file->{filename}, $id );
            $file->$id_field($id);
            $file->save();
            $count++;
        }
    }

    return $count;
}

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

    my $unmatched = $self->asset_db_class()->GetUnmatchedFiles;

    return unless ( $unmatched->size() );

    print STDERR "\nUnmatched Files in " . $self->asset_db_class()->kTable . ": \n";
    while ( $unmatched->hasNext() ) {
        my $file = $unmatched->next;
        printf( STDERR "  File: %s, Media File ID: %d, ID: %s\n",
            $file->{filename},
            $file->{media_file_id},
            $file->{id} ? $file->{id} : "<undef>"
        );
    }
}
sub remove_duplicate_assets { }

sub id_field           { assert( 0, "Virtual method, override this" ); }
sub asset_db_class     { assert( 0, "Virtual method, override this" ); }
sub get_match_criteria { assert( 0, "Virtual method, override this" ); }

1;
