// Check the status of some images on the currently rendered webpage. If the access
// to the corresponding images yields the 'in progress'-image the webservice is
// currently processing the computation of a corresponding thumbnail. In this
// case we will check periodically for 'numberOfTries' times, if the thumbnail was
// meanwhile processed. If so, the 'in progress'-image will be replaced by the
// new thumbnail
// jquerySelector is expected to be a jQuery selector string, that is: e.g. something like
//     '#thumbnail img'
// The selector expression is expected to select img-tags only!
function checkThumbnailStatusOfImagesFromJquerySelector( jquerySelector, numberOfTries ) {
	var imageInstancesToBeChecked = new Array();
	
	jQuery( jquerySelector ).each( function( i ) {
		imageInstancesToBeChecked.push( jQuery(this) ); } );
	
	checkThumbnailStatusOfImagesFromArrayOfJqueryInstances( imageInstancesToBeChecked, numberOfTries );
}

// Given one jquery instance of an image tag check, if it is representing
// a thumbnail currently being built. If so, check 'numberOfTries' times, if the building
// process is finished. If so, take care that the image is reloaded to represent the newly
// created thumbnail
function checkThumbnailStatusOfImageFromJqueryInstance( imageInstanceToBeChecked, numberOfTries ) {

	var imageInstancesToBeChecked = new Array();
	imageInstancesToBeChecked.push( imageInstanceToBeChecked );
	checkThumbnailStatusOfImagesFromArrayOfJqueryInstances( imageInstancesToBeChecked, numberOfTries );
}

// Given an array of jquery instances of image tags check, if any of the images is representing
// a thumbnail currently being built. If so, check 'numberOfTries' times, if the building
// process is finished. If so, take care that the corresponding image is reloaded to represent the newly
// created thumbnail
function checkThumbnailStatusOfImagesFromArrayOfJqueryInstances( imageInstancesToBeChecked, numberOfTries ) {
	var relationsAndResourceIds = getResourceIdImageRelations( imageInstancesToBeChecked );
	var resourceIdToImageRelations = relationsAndResourceIds.relations;
	var resourceIds = relationsAndResourceIds.resourceIds;
	
	if ( resourceIds.length > 0 ) {
		//var jsonArray = Object.toJSON( toBeChecked );
		var jsonArray = JSON.stringify( resourceIds );
		jQuery.ajax({
            url: "/AloeView/ajax/thumbnailCheck",
            type: 'get',  // get is the default type
            dataType: "json",
            data: {
	            resourceIdList: jsonArray,
	            x: new Date().getTime()
			},
			success: function( data, textStatus, jqXHR ) {
				// returned data is an array of resource ids with state info
				evaluateResultsOfThumbnailCheck( data, numberOfTries, resourceIdToImageRelations );
			},
			error: function( jqXHR, textStatus, errorThrown ) {
				// do nothing
			}
		});
	}
}

// Evaluate the results of a thumbnail check: thumbnails "in progress" will be reloaded as soon
// a the generating process is finished
function evaluateResultsOfThumbnailCheck( resourceIds, numberOfTries, resourceIdToImageRelations ) {

	var nextElementsToProcess = new Array();
	var newResourceIdToImageRelations = new Object();
	//alert( "evaluateResultsOfThumbnailCheck was called with " + resourceIds.length + " elements" );
	for ( var i = 0; i < resourceIds.length; i++ ) {
		var current = resourceIds[i];
		var currentState = current.state;
		var resourceId = current.resourceId;
		//alert( currentState + " -> " + resourceId );

		if ( currentState == "generationInProgress" ) {
			// thumbnail is currently being generated: try again later
			nextElementsToProcess.push( resourceIdToImageRelations[resourceId] );
		}
		else {
			if ( numberOfTries == 1 ) {
				// nothing to do: thumbnail exists or not
			}
			else {
				var imageElement = resourceIdToImageRelations[resourceId];
				// thumbnail was being generated and is now ready: try to reload image
				if ( imageElement != null ) {
					// get current src value
					var currentImageSrcAttribute = imageElement.attr( 'src' );
					// remove current get parameter 'dummy' (if any)
					var newImageSrcAttribute = replaceOneDummyParameterInUrlIfAny( currentImageSrcAttribute );

					// If the resource "thumbnail" is an embedded video, there might be no src attribute
					if ( newImageSrcAttribute != null ) {
						// add one dummy attribute to force reload of image (that is: avoid browser cache)
						newImageSrcAttribute += '&dummy=' + new Date().getTime();
						imageElement.attr( 'src', newImageSrcAttribute );
					}
				}
				else {  // this should not happen, but we ignore it (who knows)
					//alert( "Could not find image for resource " + resourceId );
				}
			}
		}
	}
	
	//alert( "Length is " + nextIds.length + ", number of tries is " + numberOfTries + "." );
	if ( nextElementsToProcess.length > 0 && numberOfTries > 0 ) {
		//alert( "Function checkThumbnailStatusOfImagesFromArrayOfJqueryInstances is to be called again in 3 seconds with " + nextElementsToProcess.length + " elements" );
		window.setTimeout( function() {checkThumbnailStatusOfImagesFromArrayOfJqueryInstances( nextElementsToProcess, numberOfTries-1 );}, 5*1000 );
	}
}

// Eliminate one GET parameter dummy=xxx in a URL given as string
function replaceOneDummyParameterInUrlIfAny( oldUrl ) {
	var newUrl = null;
	
	if ( oldUrl != null ) {
		newUrl = oldUrl.replace( /(\&|\?)dummy[^&]+/, "" );
	}
	return( newUrl );
}

//From parameter 'arrayOfImageJqueryInstances' extract all images i where attribute 'src'
//contains resourceThumbnailSmall or resourceThumbnailLarge. Extract the corresponding resource
//id r from the src attribute
//Returned is an object o, where
//o.resourceIdsToCheck  is an array of resource ids that represent 'in-progress'-candidates
//o.resourceIdToImageRelations  is a hash map with key value pairs (r,i) for each resource
//id r in o.resourceIdsToCheck
function getResourceIdImageRelations( arrayOfImageJqueryInstances ) {
	var result = new Object();

	var resourceIdsToCheck = new Array();
	var resourceIdToImageRelations = new Object();
	
	//alert( "Images given: " + arrayOfImageJqueryInstances.length );
	for ( var i = 0; i < arrayOfImageJqueryInstances.length; i++ ) {
		//var current = jQuery( arrayOfImageJqueryInstances[i] );
		var current = arrayOfImageJqueryInstances[i];
		var sourceAttribute = current.attr( 'src' );
		if ( sourceAttribute != null && ( sourceAttribute.indexOf( "esourceThumbnailSmall?" ) >= 0 ||
				sourceAttribute.indexOf( "esourceThumbnailLarge?" ) >= 0 ) ) {
			var matchArray = sourceAttribute.match( /contentID=([^&]+)/ );
			if ( matchArray != null ) {
				var idToUse = matchArray[1];
				resourceIdsToCheck.push( idToUse );
				resourceIdToImageRelations[idToUse] = current;
			}
		}
	}
	
	result.relations = resourceIdToImageRelations;
	result.resourceIds = resourceIdsToCheck;
	
	return( result );
}

// Get the standard thumbnail image e.g. on a resource detailed page as jQuery instance
function getThumbnailImageElement() {
	return( jQuery( '#thumbnail img' ) );
}

// Well: invalidation is done via simply reloading the image. The resource thumbnail is expected
//   to be invalidated already (at AloeMultimediaService)
function invalidateThumbnail( resourceId ) {
	var imageElement = jQuery( '#thumbnail img' );
	var sourceAttribute = imageElement.attr( 'src' );
	var newSourceAttribute = replaceOneDummyParameterInUrlIfAny( sourceAttribute ) + "&dummy=" + new Date().getTime();
	//alert( newSourceAttribute );
	imageElement.attr( 'src', newSourceAttribute );
}

function createResourceThumbnailFromMetaMetadataSet(resourceId, metadataSetId){
	jQuery.ajax({
        url: "/AloeView/ajax/createResourceThumbnailFromMetaMetadataSet",
        type: 'get',  // get is the default type
        data: {
			resourceId: resourceId,
			metadataSetId: metadataSetId
		},
		success: function( data, textStatus, jqXHR ) {
			// do nothing
		},
		error: function( jqXHR, textStatus, errorThrown ) {
			// do nothing
		}
	});
}

function createResourceThumbnailFromResource(event, resourceId, thumbnailSourceResourceId, errorMessage){
	jQuery.ajax({
        url: "/AloeView/ajax/createResourceThumbnailFromResource",
        type: 'get',  // get is the default type
        data: {
			resourceId: resourceId,
			thumbnailSourceResourceId: thumbnailSourceResourceId
		},
		success: function( data, textStatus, jqXHR ) {
			var response = data;
			if ( response == 'Okay' ) {
			    invalidateThumbnail( resourceId );
			    checkThumbnailStatusOfImageFromJqueryInstance( getThumbnailImageElement(), 10 );
			}
			else {
			    if ( event != null && errorMessage != null ) {
				popupAtMouse( errorMessage, event, -20, -100 );
			    }
			}
		},
		error: function( jqXHR, textStatus, errorThrown ) {
			alert ("failed");
		}
	});	
}


