#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::MapFace::Command::Approve;

use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::DB::Item::MapFaceFile;
use Common::DB::Item::MapFaceMapping;
use Common::DB::Item::MapFaceMappingCriteria;
use RSApache::Response::XSLT;
use Common::RSApp;

use lib '/app/tools/raptor/lib';
use Raptor::DB::Item::File;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::MapFaceTempMapping;
use RPS::DB::Item::MapFaceTempMappingCriteria;
use RPS::DB::Item::MapFaceTempMappingHistory;
use RPS::DB::Item::SaleImportError;
use RPS::DB::Item::SaleImportErrorRawValue;
use RPS::MapFace::Command::Map;
use RPS::MapFace::Command::Main;
use RPS::MapFace::Job::Mapper;
use RPS::MapFace::Mapper;
use RPS::Command;
use RPS::CommandLog;
use base 'RPS::Command';

use constant kTemplate => '/app/tools/rps/templates/mapface/map.xsl';

sub cmd  { return "approve"; }
sub area { return "mapface"; }

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 $mapID = $self->getParam('mapID');
	my $userID = Common::RSApp::GetActiveUserID();

	my $mapping = RPS::DB::Item::MapFaceTempMapping->Lookup(mapface_temp_mapping_id => $mapID);
	
	$mapping->status(RPS::DB::Item::MapFaceTempMapping::STATUS_APPROVED);
	$mapping->approving_user_id($userID);
	$mapping->save();
	
	my $fileID = $mapping->file_id;
	my $groupNum = $mapping->group_num;	
	
	# And add the event to this history.
	my $newHistoryAction = RPS::DB::Item::MapFaceTempMappingHistory->Create(
		mapface_temp_mapping_id => $mapID,
		user_id => $userID,
		action  => RPS::DB::Item::MapFaceTempMappingHistory::kActionApproved,
	);
	
	$newHistoryAction->save();	

	my $approvedCount = RPS::DB::Item::MapFaceTempMapping->GetApprovedCountByFileID($fileID);
	
	my $clientID = Common::RSApp::GetClientID();
	
	my $unapprovedCount;
	
	# Update the mapface_file entry in RSCOMMON
	my $mapFaceFileID;
	my $mapFaceFiles = Common::DB::Item::MapFaceFile->GetByClientAndFileID($clientID,$fileID);
	while ($mapFaceFiles->hasNext() ) {	
    	my $mapFaceFile = $mapFaceFiles->next();
    	$mapFaceFile->approved_mappings($approvedCount);
    	$mapFaceFile->approving_user_id($userID);
    	$unapprovedCount = $mapFaceFile->initial_errors - $approvedCount;
		$mapFaceFile->save();		
		$mapFaceFileID = $mapFaceFile->mapface_file_id;
	}		
		
	# If everything has been approved, head back to the main page.	
	if ($unapprovedCount == 0) {		
		# But first publish the mapping to RSCOMMON
		my $file = Raptor::DB::Item::File->Lookup(file_id => $fileID);
		
		my $tempMappings = RPS::DB::Item::MapFaceTempMapping->GetByFileID($fileID);
		
		while ($tempMappings->hasNext() ) {	
			my $tempMapping = $tempMappings->next();
			
			# Let's make sure we mapped something first.
			if ($tempMapping->service_id || $tempMapping->product_type || $tempMapping->format_type ||
				$tempMapping->media_type || $tempMapping->country_code) {
				my $publishedMapping = Common::DB::Item::MapFaceMapping->Create(
					service_id => $file->service_id, # Note that this is not the service that was mapped
					version_num => $file->version_num,
				  	mapped_service_id => $tempMapping->service_id,
				  	mapped_product_type => $tempMapping->product_type,
				  	mapped_format_type => $tempMapping->format_type,
				  	mapped_media_type => $tempMapping->media_type,
				  	mapped_country_code => $tempMapping->country_code,
				);
				$publishedMapping->save();		
				
				# We also need to save the values that were mapped.			
				my $rawValues = RPS::DB::Item::MapFaceTempMappingCriteria->GetAllByMappingID($tempMapping->mapface_temp_mapping_id);
				while ($rawValues->hasNext() ) {				
					my $rawValue = $rawValues->next();
					my $mappingCriteria = Common::DB::Item::MapFaceMappingCriteria->Create(
						mapface_mapping_id => $publishedMapping->mapface_mapping_id, 
						field => $rawValue->field,
						value => $rawValue->value,
					); 
					$mappingCriteria->save();									
				}	
			}
		}
		
		# Now apply the mappings to this file.
		my $mapper = RPS::MapFace::Mapper->new(fileID => $fileID);
		$mapper->run();	
		
		# Now kick off some jobs to check these mappings against the on hold files for all clients.
		my %clientIDs;
		my $mapFaceFiles = Common::DB::Item::MapFaceFile->GetAllForMapping();
		while ($mapFaceFiles->hasNext() ) {				
			my $mapFaceFile = $mapFaceFiles->next();	
			$clientIDs{$mapFaceFile->client_id} = 1;
		}
		
		foreach my $clientID (keys %clientIDs) { 
			# Create a job for this client.
			my $mapperJob = RPS::MapFace::Job::Mapper->new(clientID => $clientID);	
			$mapperJob->enqueue()
		}
		
		my $successMessage = RPS::Message->new(type => "success", code => Common::FormObject::kSuccessFormSubmit);		
		my $command = RPS::MapFace::Command::Main->new(msg => $successMessage->toString(), Highlight => $mapFaceFileID);
		return RSApache::Response::Redirect->new($command->getRedirect());		
		
	} else {	
		# Otherwise, go to the next one.
		my $nextGroup = RPS::DB::Item::MapFaceTempMapping->GetNextViewableGroupNum($fileID, $groupNum);
		if (!$nextGroup) {
			# Go back to the first page, I guess?
			$nextGroup = RPS::DB::Item::MapFaceTempMapping->GetFirstViewableGroupNum($fileID);	
		}
	
		my %mapParams = (
			file => $fileID,
			mappingGroup => $nextGroup,
		);
		my $command = RPS::MapFace::Command::Map->new(%mapParams);
		return RSApache::Response::Redirect->new($command->getRedirect());
	}
}


1;
