/*
PiAnoS (Picture Annotation System), A fingerprint examiner training tool
Copyright (C) 2011-2012 University of Lausanne, Switzerland
https://ips-labs.unil.ch/pianos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see http://www.gnu.org/licenses/.
*/


function Pianos4_Report(params)
{
	params = params || {};
	if (!params.p4) alert('Parameters to the PiAnoS 4 instance must be passed in');
	
	this.run = function()
	{
		log('Doing report in '+params.p4.phase);
	
		showMainDialog();
		//ajaxUpload();
		//myAjaxDownload();
		//ajaxDownload();
	}
	
	var self = this;

	var makeDialogSection = function(type, title, description, image, preCallback)
	{
		var left = $('<div />');
		
		left.append($('<h3 />').css('margin','0 0 0.5em 0').text(title))
			.append($('<p />').css('margin-top','0.5em').text(description));
			
		var right = $('<div />').css('float','right').css('width','128px').css('height','128px').css('margin-left','0.5em')
			.css('background-color','yellow');
			
		
		var leftDown = false;

		var onDocMouseUp = function()
		{
			leftDown = false;
			$(document).unbind('mouseup', onDocMouseUp);
			log('unbinding');
		}

		var section = $('<div />')
			.addClass('report_section')
			.addClass('ui-state-default ui-corner-all')
			.css('padding','1em')
			.css('cursor','pointer')
			.css('margin-bottom','1em')
			.hover(function() { // in
				$(this).addClass('ui-state-hover');
				if (leftDown)
					$(this).addClass('ui-state-active');
			}, function() { // out
				$(this).removeClass('ui-state-hover ui-state-active');
			})
			.on('mousedown', function() {
				$(this).addClass('ui-state-active');
				leftDown = true;
				$(document).bind('mouseup', onDocMouseUp);
			})
			.on('mouseup', function(e) {
				$(document).unbind('mouseup', onDocMouseUp);
				var activated = leftDown;
				leftDown = false;
				
				if (activated)
				{
					if (preCallback)
						preCallback();
					generateReport(type);
				}
				
			})
		;
		
		section
			.append(right)
			.append(left)
			.append($('<div />').css('clear','both'))
			.disableSelection();
			
		return section;
	}
	
	var showMainDialog = function()
	{
		var content = $('<div />');
	
		var dlg = $('<div />')
			.append(content);
			
		var closeDialogCB = function() {
			dlg.dialog('close');
		};
		
		content.append(makeDialogSection('analysis', 'Analysis', 'A report on the analysis phase with quite a lengthy explanation on how it works, what it does and what\'s the menu for today.', null, closeDialogCB));
		
		if (params.p4.phase != 'analysis')
		{
			content.append(makeDialogSection('comparison', 'Comparison', 'A report on the comparison phase. Obviously, this is only available when the comparison is at least started.', null, closeDialogCB));
		}
					
		pianos.dialog(dlg, {
			modal: true,
			title: 'Choose the report to generate',
			width: 500,
			close: function() { $(this).remove(); },
			buttons: {
				'Cancel': function() {
					$(this).dialog('close');
				},
			}
		});
	}
	
	var generateReport = function(type)
	{
		log('Generating '+type+' report');
		
		var serializeSVG = function(node)
		{
			if (typeof window.XMLSerializer != 'undefined')
				return (new window.XMLSerializer()).serializeToString(node);
			else if ('xml' in node)
				return node.xml;
			else
				throw 'Your crappy browser is not able to fetch the XML string from an SVG node. Please get a real computer.';
		}
		
		var src_data = [
			{ type: 'mark', nodesel: '.pianos4_mark svg' }
		];
		if (type == 'comparison')
			src_data.push(
			{ type: 'print', nodesel: '.pianos4_print svg' }
			);
			
		
		var data = {
			type: type,
			xml: {},
		};
		
		for (var i in src_data)
		{
			var item = src_data[i];
			var node = d3.select(item.nodesel).node();
			var xml = serializeSVG(node);
			data.xml[item.type] = xml;
		}
		
		log(data);
		ajaxUpload(data);
	}
	
	var ajaxDownload = function()
	{
		$.fileDownload(params.p4.reportToolURL);
	}
	
	var myAjaxDownload = function()
	{
		var iframe = $('<iframe />')
			//.css('display','none')
			.css('position','absolute')
			.css('top',0)
			.css('right',0)
			.css('width','300px')
			.css('height','200px')
			.css('z-index','2000')
			.addClass('ui-widget ui-widget-content')
			.attr('src', params.p4.reportToolURL)
			//.append($('<script />').attr('type','text/javascript').text("$(document).ready(function() { alert('toto'); });"))
			//.append('<body />')
		;
			
		iframe.appendTo($('body'));
	}
	
	var ajaxUpload = function(data)
	{
		pianos.ajax({
			url: params.p4.reportToolURL,
			data: JSON.stringify(data),
			type: 'post',
			processData: false,
			contentType: 'application/json',
			dataType: 'json',
			success: function(data)
			{
				if (data.error)
				{
					showErrorMessage('rpc', data.message);
				}
				else
				{
					log(data.ret);
				}
			},
			error: function(xhr, status, error)
			{
				showErrorMessage('http', status, error);
			},
		});
	
	}

	var showErrorMessage = function(errtype, p1, p2)
	{
		log('Report generation failed ! Details:');
		
		var title = 'error';
		var content = $('<div />');
		var message = 'Unspecified error';
		
		if (errtype == 'http')
		{
			message = p1 != 'error' ? (p1 != p2 ? p1 + '\n' + p2 : p2) : p2;
			title = 'HTTP error';
		}
		else
		{
			message = p1;
			title = 'Unhandled exception';
		}
		
		content.append(
			$('<div />')	
				.text(message)
				.css('font-family', 'courier new')
				.css('white-space', 'pre-wrap')
				.css('word-wrap', 'break-word')
				.css('font-size', '0.75em')
				.css('margin','0.5em')
		).addClass('ui-state-error');
		
		var dlg = $('<div />')
			.append(content);
					
		pianos.dialog(dlg, {
			modal: true,
			title: title,
			width: 500,
			close: function() { $(this).remove(); },
			buttons: {
				'OK': function() {
					$(this).dialog('close');
				},
			}
		});
	}
}
