/*
 * 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/.
 */

/**
 * @constructor
 */
function Pianos4ToolLR( params )
{
	// ------------------------------
	// Constructor
	// ------------------------------
	
	// ------------------------------
	// Public methods
	// ------------------------------
	
	this.getName = function()
	{
		return 'LR';
	}

	this.getLabel = function()
	{
	    if( pianos.getParams().phase == "analysis" )
	        return 'ESLR';
	    else
	        return 'LR';
	}

	this.getIcon = function()
	{
	    if( pianos.getParams().phase == "analysis" )
	        return 'icons/tool_ESLR.png';
	    else
	        return 'icons/tool_LR.png';
	}

	this.bind = function( aView )
	{
		assert( !view );
		view = aView;
	}

	this.unbind = function()
	{
		assert( view );
		view = null;
	}

	this.activate = function()
	{
	    needToCheckClusterState = true;
	}

	this.deactivate = function()
	{
	    needToCheckClusterState = false;
	}

	this.onMouseDown = function( pos, target, event )
	{
	}

	this.onMouseMove = function( pos, target )
	{
	}

	this.onMouseUp = function( pos, target, event )
	{
	}

	this.cancel = function()
	{
	}

	this.getOptionsPanel = function()
	{
		if( !options )
		{
			panel = $( '<div />' ).addClass( 'pianos4_NIST_options' );
			
			var div = $( '<div />' );
			
			// sumbit
			var submitter = $( '<a />' ).text( 'send' ).attr( 'href', '#lr' ).bind( 'click', function( e )
			{
				e.preventDefault();

				if( pianos.getParams().phase == "analysis" )
				{
				    var tempData = returnData();

				    for( var i in tempData.mark.minutiae )
		            {
				        tempData.mark.minutiae[ i ].pairing = tempData.mark.minutiae[ i ].id;
		            }
				    tempData.print = tempData.mark;
		            
				} else {
				    restartNumbering();
				    var tempData = returnData();
				}
				
				if( checkData( tempData ) == true )
				{
					var lrdata = {};
					
					lrdata.data = toJSON( tempData );
					lrdata.exid = getURLParameter( 'id' );
					lrdata.userId = pianos.getUser()[ 'id' ];
					lrdata.userName = pianos.getUser()[ 'name' ];
					lrdata.userEmail = pianos.getUser()[ 'email' ];
					lrdata.caseName = pianos.getCaseName();
					lrdata.markId = pianos.getMarkInformation()[ 'id' ];
					lrdata.printId = pianos.getPrintInformation()[ 'id' ];
					lrdata.phase = pianos.getParams().phase;
					
					$.ajax(
		            {
		                dataType: 'json',
		                type: 'POST',
		                data: lrdata,
		                url: '?action=lr',
		                success: function( d )
		                {
		                    if( d.error == false )
		                        toastr.success( d.data.id, "Data successfully sended to Xena", { timeOut: 10000 } );
		                    else
		                        toastr.error( d.message, "Xena error", { timeOut: 10000 } );
		                },
		                error: function()
		                {
		                    toastr.error( "Network error" );    
		                }
		            } );
				}
			} );
			
			// Getter
			var getter = $( '<a />' ).text( 'get' ).css( 'text-decoration', 'underline' ).css( 'cursor', 'pointer' ).on( 'click', function()
	        {
			    onGetLRs();
	        } ); 
			
			// Cluster status
			var statusdiv = $( '<div />' )
			    .css( 'margin-top', '5px' )
			    .css( 'display', 'grid' )
			    .css( 'grid-template-columns', '30px auto' )
			    .css( 'align-items', 'center' )
			    .append(
		            $( '<div />' )
		                .text( 'State: ' )
                )
			    .append(
		            $( '<div />' )
		                .attr( 'id', 'clusterstatus' )
	            );
			
			// Composition
			div.append( submitter );
			div.append( '<br />' );
			div.append( getter );
			div.append( '<br />' );
			div.append( statusdiv );
			
			// panel
			panel.append( div );
			
			options = panel;
		}
		
		return options;
	}
	
	this.afterLoaded = function()
	{
	    $( '#clusterstatus' ).empty();
	    
	    var svgContainer = d3.select( '#clusterstatus' )
            .append( 'svg' )
            .attr( 'width', 32 )
            .attr( 'height', 16 );
	    
	    svgContainer.append( "circle" )
	        .attr( 'id', 'clusterinput' )
	        .attr( "cx", 8 )
            .attr( "cy", 8 )
            .attr( "r", 8 )
            .attr( 'fill', '#006DF0' );
        
        checkClusterState();
	}
	
	this.getHelp = function()
	{
		return Pianos4Help.compile( [
			''
		] );
	}

	// ------------------------------
	// Private variables
	// ------------------------------
	
	var self = this;
	var view = null;
	var options = null;
	
	var serverData = null;
	var serverDataIdx = null;
	
	var panel = null;
	var form = null;
	var downloadData = null;
	var exidData = null;
	
	var needToCheckClusterState = true;
	
	// ------------------------------
	// Private functions
	// ------------------------------
	
	var checkClusterState = function()
	{
	    if( needToCheckClusterState )
        {
    	    $.ajax(
            {
                dataType: 'json',
                type: 'GET',
                url: pianos.getParams().Xena_api_state,
                success: function( d )
                {
                    var col = "";
                    if( d.data.Inputer === 'green' && d.data.Linux === 'green' && d.data.DMA !== 'red' )
                        col = '#109618';
                    
                    else if( d.data.Inputer === 'red' || d.data.Linux === 'red' || d.data.DMA === 'red' )
                        col = '#dc3912';
                    
                    else
                        col = '#ff9900';
                    
                    $( '#clusterinput' )
                        .css( 'fill', col );
                },
                error: function()
                {
                    $( '#clusterstatus > svg > circle' )
                        .css( 'fill', '#dc3912' );    
                }
            } );
    	    
    	    setTimeout( checkClusterState, 5000 );
        }
	}
	
	var returnData = function()
	{
		var data = pianos.getData();
		
		for( k in data )
		{
			if( k != "mark" & k != "print" )
			{
				delete data[ k ];
			} else {
			    for( var j in data[ k ] )
			        if( j != "image" && j != "minutiae" )
			            delete data[ k ][ j ];
			}
		}

		return data;
	}
	
	var toJSON = function( data )
	{
		return JSON.stringify( data )
	}
	
	var restartNumbering = function()
	{
		var batch = new Pianos4Action_Batch( 'Restart numbering' );
		var pairs = {};
		Pianos4Annotation._s_pairIds = 1;
		
		var mark = pianos.getView( 'mark' );
		var mannotations = mark.getAllAnnotations();
		for( var id in mannotations )
		{
			var a = mannotations[ id ][ 1 ];
			if( 'pairing' in a )
			{
				assert( mannotations[ id ][ 0 ] == 'minutia' );
				pairs[ a.pairing ] = a;
			}
		}
		
		var print = pianos.getView( 'print' );
		var pannotations = print.getAllAnnotations();
		for( var id in pannotations )
		{
			var a = pannotations[ id ][ 1 ];
			if( 'pairing' in a )
			{
				assert( pannotations[ id ][ 0 ] == 'minutia' );
				assert( a.pairing in pairs );
				var action = new Pianos4Action_PairMinutiae( pairs[ a.pairing ], a, Pianos4Annotation._s_pairIds++ );
				batch.append( action );
			}
		}
		
		pianos.exec( batch );
	}
	
	var checkData = function( data )
	{
		// Center
		hasCenter = false;
		
		for( m in data.print.minutiae )
		{
			if( data.print.minutiae[m].type == "center" )
			{
				hasCenter = true;
				break;
			}
		}

		// Number of paired minutiae above the minimum of the calculator
		paired = 0;
		
		for( m in data.print.minutiae )
		{
			if( data.print.minutiae[m].type != "center" & data.print.minutiae[m].type != "difference" & data.print.minutiae[m].pairing !== undefined )
				paired += 1;
		}
		
		minPaired = paired >= 4;
		
		// Post processing
		if( hasCenter == false )
		{
		    if( pianos.getParams().phase == "analysis" )
		        toastr.error( "You need to annotate the center on the mark" );
		    else
		        toastr.error( "You need to annotate the center on the print" );
		    
			return false;
		} else if ( minPaired == false )
		{
			toastr.error( "At least 4 minutiae have to be paired" );
			return false;
		} else {
			return true;
		}
	}
	
	var onGetLRs = function()
    {
        var complete = function( data )
        {
            var dlgopts = {
                autoOpen : true,
                modal : false,
                width : 800,
                title : 'All LRs',
                close : function()
                {
                    $( this ).remove();
                },
                buttons : {
                    'Reload' : function()
                    {
                        $( this ).dialog( 'close' );
                        return onGetLRs();
                    },
                    
                    'Close' : function()
                    {
                        $( this ).dialog( 'close' );
                    }
                },
            };
            
            if( !data || data.error )
            {
                alert( "no data or data.error" );
            } else {
                var div = $( '<div />' );
                var id_base = 'pianos4_resultdlg_opt_' + ( new Date().getTime() );
                
                div.qtable( {
                    data : processing( data.ret ),
                    columnMode : 'mapping',
                    columns : [
                        {
                            title : 'Id',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].id );
                            }
                        },
                        {
                            title : 'PDF',
                            render : function( data, i, j, cell )
                            {
                                cell.append( $( '<a />' ).text( 'PDF' ).attr( 'href', '?action=getlrpdf&id=' + data[ i ].id ) );
                            }
                        },
                        
                        {
                            title : 'Time',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].time );
                            }
                        },
                        
                        {
                            title : 'Minutiae count',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].nb_min );
                            }
                        },
                        
                        {
                            title : 'Bending Energy',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].be );
                            }
                        },
                        
                        {
                            title : 'Type',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].modeltype );
                            }
                        },
                        
                        {
                            title : 'Value',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].LR );
                            }
                        },
                        
                        {
                            title : 'Log Value',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].log10_LR );
                            }
                        },
                    ],
                } );
                
                var dlg = $( '<div />' )
                    .addClass( 'pianos4_dialog' )
                    .css( 'max-height', $( window ).height() - 140 )
                    .append( div );
                
                dlg.dialog( dlgopts );
            }
        }

        var processing = function( data )
        {
            var ret = [];
            
            for( var i in data )
            {
                var d = data[ i ];
                
                ret.push( {
                    user : d.user,
                    id : d.id,
                    modeltype : d.modeltype,
                    time : d.time,
                    nb_min : parseInt( d.nb_min ),
                    be : parseFloat( d.Be ).toFixed( 4 ),
                    LR : parseFloat( d.LR ).toExponential( 4 ),
                    log10_LR : Math.log10( parseFloat( d.LR ) ).toFixed( 4 ),
                } );
            }
            
            return ret;
        }
        
        $.ajax( {
            pendingMessage : 'Loading LRs from database',
            url : '?action=rpc&method=getLRUsers&exid=' + pianos.getCaseID() + '&uid=' + pianos.getUser()[ 'id' ],
            dataType : 'json',
            success : function( data )
            {
                complete( data );
            },
            error : function()
            {
                alert( "ajax error" );
            }
        } );
    }
}
