#!/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 $VAR1;
my $bigEval;
while (my $line = <STDIN>)
{
	chomp $line;
	$bigEval .= $line;
}

eval $bigEval;

#print Dumper($VAR1) . "\n";

my $clientID = $VAR1->[0]->{mapping}{client_id};
print "CLIENT ID $clientID\n";


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

foreach my $record (@$VAR1)
{
	# Now, FIND THAT PRODUCT!!!!

	my $product = RPS::DB::Item::Product->Lookup
	(
		asset_id => $record->{mapping}{client_site_id},
		product_type_id => $record->{cm_product}{product_type_id},
	);

	if (! $product)
	{
		print "ERROR : can't find product for this record: " . Dumper($record) . "\n";
		next;
	}

	# Sanity check the upc
	# !!! Might need to move some state over.
	#
#	if ($product->upc_ean ne $record->{cm_product}{upc_ean}
#	 || $product->product_code ne $record->{cm_product}{product_code})
#	{
#		print "ERROR : these products don't appear to match: " . Dumper($product) . "\n" . Dumper($record) . "\n\n";
#	}


	# Check for dups - maybe we have this product mapped already?
	#
	my $dup = Common::DB::Item::ClientCMIDMap->Lookup(client_id => $clientID, client_site_id => $product->product_id, id_type=>'product_id');
	if ($dup)
	{
		print "WE HAVE THIS MAPPED: " . Dumper($dup) . "\n" . Dumper($product) . "\n" . Dumper($record) . "\n\n";
	}

	# Now make the mapping.
	#
	my $newMapping = Common::DB::Item::ClientCMIDMap->Create
	(
		client_id => $clientID,
		client_site_id => $product->product_id,
		cm_site_id => $record->{cm_product}{product_id},
		id_type => 'product_id',
	);
	$newMapping->save();
}

