#!/usr/bin/perl
use strict;

use Proc::Pidfile;
use Text::ParseWords;
use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::RSApp;
use Common::Log;
use Common::DB::Item::TableChangeLog;
use Common::DB::Item::Client;
use Common::DB::Item::ClientType;
use Common::DB::Item::ClientCMIDMap;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Track;
use RPS::DB::Item::Album;
use RPS::DB::Item::Product;
use RPS::DB::Item::Master;
use RPS::DB::Item::Song;
use RPS::DB::Item::Artist;
use RPS::DB::Item::Composer;
use RPS::DB::Item::Label;
use RPS::DB::Item::ProductTrack;

use constant kCMClientID => 112;

my $singleton = Common::RSApp->new( clientID => kCMClientID );

my %gMissingProductMap;
my %gReport;

my $allProducts = RPS::DB::Item::Product->GetAll();
while ( my $product = $allProducts->next() ) {

    # First, I have to figure out which client this product originally belonged to.
    #
    my $allMappings = Common::DB::Item::ClientCMIDMap->GetAll(
        "select * from client_cm_id_map where id_type='product_id' and cm_site_id=" . $product->product_id );
    if ( 1 != $allMappings->size() ) {
        print "ERROR : got " . $allMappings->size() . " mappings for product " . $product->product_id . "\n";

        # Apparently we have a crapload of products in the CM database that lack a mapping.
        # Perhaps we can figure out what that mapping should look like, and create it?
        #
        if ( RPS::DB::Item::Product::kProductTypeDigitalTrack == $product->product_type_id ) {

            # Do we perhaps have a mapping for the track?
            # !!! Hopefully just 1
            #
            my $trackMaps = Common::DB::Item::ClientCMIDMap->GetAll(
                "select * from client_cm_id_map where id_type='track_id' and cm_site_id=" . $product->asset_id );
            if ( 1 != $trackMaps->size() ) {
                print "ERROR : got "
                  . $trackMaps->size()
                  . " mappings for product "
                  . $product->product_id
                  . ", track "
                  . $product->asset_id . "\n";
                $gReport{cannotFindDistinctTrackMap}++;
                next;
            }

            my $mapping  = $trackMaps->next();
            my $clientID = $mapping->client_id;

            # So, here's the tricky part:
            # I will now need to find the track product in the client's original database, so I can map the ids.
            # !!! Leave that for now.
            push @{ $gMissingProductMap{$clientID} },
              {
                cm_product => $product,
                mapping    => $mapping
              };

            $gReport{willCreateNewTrackProductMap}++;
            next;
        } else {

            # Do we perhaps have a mapping for the album?
            # !!! Hopefully just 1
            #
            my $albumMaps = Common::DB::Item::ClientCMIDMap->GetAll(
                "select * from client_cm_id_map where id_type='album_id' and cm_site_id=" . $product->asset_id );
            if ( 1 != $albumMaps->size() ) {
                print "ERROR : got "
                  . $albumMaps->size()
                  . " mappings for product "
                  . $product->product_id
                  . ", album "
                  . $product->asset_id . "\n";
                $gReport{cannotFindDistinctAlbumMap}++;
                next;
            }

            my $mapping  = $albumMaps->next();
            my $clientID = $mapping->client_id;

            # So, here's the tricky part:
            # I will now need to find the album product in the client's original database, so I can map the ids.
            # !!! Leave that for now.
            push @{ $gMissingProductMap{$clientID} },
              {
                cm_product => $product,
                mapping    => $mapping
              };
            $gReport{willCreateNewAlbumProductMap}++;
            next;
        }

        $gReport{noProductMap}++;
        next;
    }
    my $productMapping = $allMappings->next();
    my $clientID       = $productMapping->client_id;

    my $assetID = $product->asset_id;
    my $remappedID;
    if ( RPS::DB::Item::Product::kProductTypeDigitalTrack == $product->product_type_id ) {

        # So... the question is, have we _already_ mapped this?
        #

        my $mapping = Common::DB::Item::ClientCMIDMap->Lookup(
            client_id  => $clientID,
            id_type    => 'track_id',
            cm_site_id => $assetID,
        );
        if ($mapping) {
            $gReport{alreadyMappedTrack}++;
            next;
        } else {
            my $mapping = Common::DB::Item::ClientCMIDMap->Lookup(
                client_id      => $clientID,
                id_type        => 'track_id',
                client_site_id => $assetID,
            );
            if ($mapping) {
                $remappedID = $mapping->cm_site_id;
            } else {
                print "ERROR : no mapping for client $clientID, track_id, asset $assetID\n";
                $gReport{noTrackMap}++;
                next;
            }
        }
    } else {
        my $mapping = Common::DB::Item::ClientCMIDMap->Lookup(
            client_id  => $clientID,
            id_type    => 'album_id',
            cm_site_id => $assetID,
        );
        if ($mapping) {
            $gReport{alreadyMappedAlbum}++;
            next;
        } else {
            my $mapping = Common::DB::Item::ClientCMIDMap->Lookup(
                client_id      => $clientID,
                id_type        => 'album_id',
                client_site_id => $assetID,
            );
            if ($mapping) {
                $remappedID = $mapping->cm_site_id;
            } else {
                print "ERROR : no mapping for client $clientID, album_id, asset $assetID\n";
                $gReport{noAlbumMap}++;
                next;
            }
        }
    }

    print "REMAPING PRODUCT " . $product->product_id . " to use asset $remappedID\n";
    $gReport{wouldReMap}++;

    #	$product->asset_id($remappedID);
    #	$product->save();
}

print Dumper( \%gReport ) . "\n";

$Data::Dumper::Purity   = 1;
$Data::Dumper::Deepcopy = 1;
foreach my $cID ( keys %gMissingProductMap ) {
    open( DUMP, "> $cID.OUT" ) or die $!;
    print DUMP Dumper( $gMissingProductMap{$cID} );
    close DUMP;
}
