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

Pianos4Backend.UserHome = function( selector, params )
{
    params = params || {};
    if( !params.user )
        udb.error( 'Programming error', 'The user must be specified' );
    
    this.init = function()
    {
        buildUI();
        log( params.user );
    }

    var self = this;
    
    var buildUI = function()
    {
    	selector.addClass( 'pianos4_main' );
    	
    	var div = $( '<div />' );
    	if( params.user.switchedUser )
    		div.append( $( '<div />' ).css( 'color', 'red' ).append( $( '<h1 />' ).text( 'You are now logged as "' + params.user.name + '". All modifications are persistent. Be careful.' ) ) );
    	
    	div.append( $( '<h2 />' ).text( 'Welcome to PiAnoS, ' + params.user.name ) );
    	
    	selector.append( div );
    	
        udb
            .app()
            .getModel()
            .rpc( 'getHomeData', function( data )
            {
                var mainDiv = selector.find( '>div:first' );
                
                mainDiv.append(
                    $( '<div/>' )
                        .append(
                            $( '<p />' ).append( $( '<strong>' ).text( 'Image management' ) )
                        )
                        .append(
                            $( '<a />' )
                                .attr( 'href', '#' )
                                .text( 'Upload multiple images (mark or print) to the gallery' )
                                .button()
                                .click( function( e )
                                {
                                    e.preventDefault();
                                    Pianos4Backend.ImageManagerDropzones();
                                } )
                        )
                );
                
                if( params.user.can_create_personnal_folder )
                {
                    mainDiv.append( $( '<p />' ).append( $( '<strong />' ).text( 'Your cases' ) ) );
                    
                    if( !data.folder )
                    {
                        mainDiv.append( $( '<div />' ).append( $( '<p />' ).text( 'You need a personal folder to create your own cases (i.e. upload your own images).' ) ).append( $( '<span />' )
                            .text( 'Create one now' ).button().bind( 'click', function()
                            {
                                udb.app().getModel().rpc( 'createPersonalFolder', function()
                                {
                                    window.location.reload();
                                } );
                            } ) ) );
                    } else
                    {
                        mainDiv
                            .append( '<p><a href="#folder/' + data.folder.id + '">Your personal folder</a> contains ' + data.folder.exids.length + ' exercise' + ( data.folder.exids.length == 1 ? '' : 's' ) + '</p>' );
                    }
                } else {
                    if( params.user.can_view_personnal_folder_summary && data.folder )
                    {
                        mainDiv.append( $( '<p />' ).append( $( '<strong />' ).text( 'Your cases' ) ) );
                        mainDiv.append( '<p><a href="#folder/' + data.folder.id + '">Your personal folder</a> contains ' + data.folder.exids.length + ' exercise' + ( data.folder.exids.length == 1 ? '' : 's' ) + '</p>' );
                    }
                }
                
                var numStarted = 0, numDone = 0, numTotal = 0;
                for( var i in data.progress )
                {
                    var ex = data.progress[ i ];
                    numTotal++;
                    ex.progress.label2 = 'To do';
                    ex.progress.color = 'black';
                    if( ex.progress.status >= 4 )
                    {
                        numDone++;
                        ex.progress.label2 = 'Done !';
                        ex.progress.color = 'green';
                    } else if( ex.progress.status >= 0 )
                    {
                        numStarted++;
                        ex.progress.label2 = 'To continue';
                        ex.progress.color = 'blue';
                    }
                }
                var percent = 100.0 * numDone / numTotal;
                
                if( params.view.progress_bar )
                {
                    mainDiv.append( $( '<p />' ).append( $( '<strong />' ).text( 'Overall progress : ' ) ).append( $( '<span />' )
                        .text( numDone + ' / ' + numTotal + ' trial' + ( numDone != 1 ? 's' : '' ) + ' done' + ( numStarted ? ', ' + numStarted + ' started' : '' ) ) ) ).append( $( '<div />' )
                        .addClass( 'home_progressbar' ).progressbar( {
                            value: percent
                        } ).append( $( '<span />' ).addClass( '_percent_wrap' ).append( $( '<span />' ).addClass( '_percent' ).text( percent.toFixed( 0 ) + ' %' ) ) ) );
                }
                
                if( params.view.homeData_as_todo_list )
                	mainDiv.append( $( '<p />' ).append( $( '<strong />' ).text( 'Cases in progress:' ) ) );
                else
                	mainDiv.append( $( '<p />' ).append( $( '<strong />' ).text( 'All cases:' ) ) );
                
                var ul = $( '<ul />' );
                var ul2 = $( '<ul />' );
                for( var i in data.progress )
                {
                    var ex = data.progress[ i ];
                    
                    var li = $( '<li />' ).append( $( '<span />' ).addClass( 'home_details_status' ).append( '[ ' )
                        .append( $( '<span />' ).text( ex.progress.label2 ).css( 'color', ex.progress.color ) ).append( ' ] ' ) ).append( $( '<a />' ).attr( 'href', '#exercise/' + ex.id )
                        .text( ex.name ) );
                
                    if( params.view.homeData_as_todo_list && ex.progress.label2 == "Done !" )
                    	ul2.append( li );
            		else
	                    ul.append( li );
                    
                }
                mainDiv.append( ul );
                
                if( params.view.homeData_as_todo_list )
            	{
                	mainDiv.append( $( '<p />' ).append( $( '<strong />' ).text( 'Terminated cases:' ) ) );
                	mainDiv.append( ul2 );
            	}
                
                var withPrize = false;
                if( withPrize && numDone == numTotal )
                {
                    udb.app().getModel().rpc( 'getCompletionCode', function( code )
                    {
                        var block = $( '<div />' ).addClass( 'ui-widget' );
                        
                        $( '<div />' ).addClass( 'ui-widget-header ui-corner-top' ).css( 'padding', '0.2em 0.5em' ).text( 'Congratulations ! ' ).appendTo( block );
                        
                        var subject = 'NIJ Study completed';
                        var body = 'Hi Glenn,\n\nI\'ve completed the NIJ Study using PiAnoS. Here is my passcode:\n' + code + '\n\nPlease send me my prize!\n';
                        
                        $( '<div />' ).addClass( 'ui-widget-content ui-corner-bottom' ).css( 'padding', '0 1em' ).append( $( '<p />' )
                            .text( 'You have won a prize ! To obtain it, please send the passcode' ) ).append( $( '<p />' ).append( $( '<span />' ).addClass( 'ui-state-default' )
                            .css( 'font-weight', 'bold' ).css( 'font-family', 'courier new' ).css( 'padding', '0.5em 1.5em' ).text( code ) ) ).append( $( '<p />' ).text( 'to ' ).append( $( '<a />' )
                            .attr( 'href', 'mailto:glenn.langenburg@unil.ch?subject=' + encodeURIComponent( subject ) + '&body=' + encodeURIComponent( body ) ).text( 'glenn.langenburg@unil.ch' ) ) )
                            .appendTo( block );
                        
                        var mainDiv = selector.find( '>div:first' );
                        block.insertAfter( mainDiv.find( 'h2' ) );
                    } );
                }
                
                var lastWeekWarning = false;
                var endOfStudyWarning = false;
                
                if( lastWeekWarning )
                {
                    var block = $( '<div />' ).addClass( 'ui-widget' ).css( 'margin-top', '1em' );
                    $( '<div />' ).addClass( 'ui-widget-header ui-corner-top ui-state-error' ).css( 'padding', '0.2em 0.5em' ).text( 'Last week notice' ).appendTo( block );
                    $( '<div />' )
                        .addClass( 'ui-widget-content ui-corner-bottom ui-state-highlight' )
                        .css( 'padding', '0 1em' )
                        .append( $( '<p />' ).text( 'Dear participant,' ) )
                        .append( $( '<p />' )
                            .text( 'The study will end in at the end of the week, on Sunday, 9th. PiAnoS remains fully functional until that date, and we encourage you to finish the trials - or at least those that you have already started. Do not forget to reclaim your prize if you see the code and email link above !' ) )
                        .append( $( '<p />' ).text( 'We would like to thank you for your participation in this study. We hope you had a great time with PiAnoS !' ) ).append( $( '<p />' )
                            .text( 'Yours sincerly,' ) ).append( $( '<p />' ).text( 'The PiAnoS NIJ project team' ) ).appendTo( block );
                    var mainDiv = selector.find( '>div:first' );
                    block.insertAfter( mainDiv.find( 'h2' ) );
                }
                
                if( endOfStudyWarning )
                {
                    var block = $( '<div />' ).addClass( 'ui-widget' ).css( 'margin-top', '1em' );
                    $( '<div />' ).addClass( 'ui-widget-header ui-corner-top ui-state-error' ).css( 'padding', '0.2em 0.5em' ).text( 'Study is over !' ).appendTo( block );
                    $( '<div />' )
                        .addClass( 'ui-widget-content ui-corner-bottom ui-state-highlight' )
                        .css( 'padding', '0 1em' )
                        .append( $( '<p />' ).text( 'Dear participant,' ) )
                        .append( $( '<p />' )
                            .text( 'The study is now (2012-09-10) over. Your results have been collected and archived for analysis by our team. PiAnoS will stay open for little while, so you will still be able to log-in as usual, but further results will not be considered in the research.' ) )
                        .append( $( '<p />' )
                            .text( 'Do not forget to reclaim your prize if you see the code and email link above ! You will be notified by email when your personnal access to PiAnoS is available.' ) )
                        .append( $( '<p />' )
                            .text( 'We would like to thank you again for your participation in this study. Your contribution was very valuable to us. We hope you had a great time with PiAnoS !' ) )
                        .append( $( '<p />' ).text( 'Yours sincerly,' ) ).append( $( '<p />' ).text( 'The PiAnoS NIJ project team' ) ).appendTo( block );
                    var mainDiv = selector.find( '>div:first' );
                    block.insertAfter( mainDiv.find( 'h2' ) );
                }
            } );
    }
}

Pianos4Backend.UserExercise = function( selector, params )
{
    params = params || {};
    if( !params.id )
        udb.error( 'Programming error', 'The exercise ID must be specified' );
    if( !params.user )
        udb.error( 'Programming error', 'The user must be specified' );
    
    this.init = function()
    {
        buildUI();
    }

    var self = this;
    
    var buildUI = function()
    {
        udb.app().getModel().rpc( 'getExercise', {
            id: params.id,
            withProgress: true
        }, function( ex )
        {
            log( ex );
            
            var label;
            if( ex.progress.status >= 4 )
                label = 'Review your results';
            else if( ex.progress.status >= 0 )
                label = 'Resume your work';
            else
                label = 'Start this exercise';
            
            var div = $( '<div />' ).append( $( '<h2 />' ).text( ex.name ) ).append( $( '<p />' ).addClass( 'exercise_description' ).text( ex.description ) ).append( $( '<span />' )
                .addClass( 'pianos4_image_preview' ).append( $( '<img />' ).attr( 'src', '?action=get_image&thumb&id=' + ex.mark ).attr( 'alt', 'Mark image' ) ) ).append( $( '<span />' )
                .addClass( 'pianos4_image_preview' ).append( $( '<img />' ).attr( 'src', '?action=get_image&thumb&id=' + ex.print ).attr( 'alt', 'Print image' ) ) ).append( $( '<div />' )
                .css( 'margin-top', '1em' ).append( $( '<a />' ).attr( 'href', '?action=take&id=' + ex.id ).text( label ).button() ) );
            
            if( !params.user.tutor )
            {
                if( ex.ownerid == params.user.id )
                {
                    var canClone = ex.progress.status >= 3;
                    div.find( 'div:last' ).append( $( '<a />' ).css( 'margin-left', '1em' ).attr( 'href', '#exercise/' + ex.id + '/edit' ).text( 'Edit case' ).button() ).append( $( '<a />' )
                        .css( 'margin-left', '1em' ).attr( 'href', '#exercise/' + ex.id + '/clone' ).text( 'Re-use analysis in a new case' ).button( {
                            'disabled': !canClone
                        } ) );
                }
                
                if( 'reuse_analysis' in ex )
                {
                    var canReuse = ex.reuse_analysis.length > 0;
                    div.find( 'div:last' ).append( $( '<a />' ).css( 'margin-left', '1em' ).attr( 'href', '#' ).text( 'Use analysis from another case' ).button( {
                        'disabled': !canReuse
                    } ).click( function( e )
                    {
                        e.preventDefault();
                        pickReusableExercise( ex )
                    } ) )
                }
            }
            
            selector.addClass( 'pianos4_main' ).append( div );
        } );
    }

    var pickReusableExercise = function( ex )
    {
        assert( ex.reuse_analysis.length );
        log( 'picking reusable thing of exercise:' );
        log( ex );
        
        var dlg = $( '<div />' );
        
        $( '<p />' ).text( 'Please choose a case from which the analysis phase should be copied.' ).appendTo( dlg );
        
        var nav = $( '<div />' ).css( 'margin-bottom', '0.5em' ).appendTo( dlg );
        var prev = $( '<span />' ).text( '<<' ).button().css( 'margin-right', '1em' ).css( 'display', 'inline-block' ).css( 'width', '15%' ).appendTo( nav );
        var exname = $( '<span />' ).text( 'Loading,please wait ...' ).css( 'display', 'inline-block' ).css( 'width', '50%' ).appendTo( nav );
        var next = $( '<span />' ).text( '>>' ).button().css( 'margin-left', '1em' ).css( 'display', 'inline-block' ).css( 'width', '15%' ).appendTo( nav );
        
        var onbutton = function()
        {
            var newindex = $( this ).data( 'pianos-ex-index' );
            assert( typeof newindex != 'undefined' && newindex !== null );
            select( newindex );
        }

        prev.button( 'disable' ).click( onbutton );
        next.button( 'disable' ).click( onbutton );
        
        var frame = $( '<div />' ).css( 'width', 200 ).css( 'height', 350 ).appendTo( dlg );
        
        var iframe = null;
        
        var select = function( index )
        {
            assert( index >= 0 && index < ex.reuse_analysis.length );
            if( iframe )
            {
                frame.find( '*' ).remove();
                iframe = null;
            }
            
            var a = ex.reuse_analysis[ index ];
            exname.text( a.name ).data( 'pianos-aid', a.progress.aid );
            
            if( index > 0 )
                prev.data( 'pianos-ex-index', index - 1 ).button( 'enable' );
            else
                prev.data( 'pianos-ex-index', null ).button( 'disable' );
            if( index < ex.reuse_analysis.length - 1 )
                next.data( 'pianos-ex-index', index + 1 ).button( 'enable' );
            else
                next.data( 'pianos-ex-index', null ).button( 'disable' );
            
            var container = $( '<div />' ).appendTo( frame );
            iframe = new Pianos4Backend.IFrame( container, a.progress.aid );
            iframe.init();
        }

        dlg.dialog( {
            autoOpen: true,
            modal: true,
            title: 'Re-use analysis from another case',
            buttons: {
                'OK': function()
                {
                    var aid = exname.data( 'pianos-aid' );
                    udb.app().getModel().rpc( 'reuseAnalysis', {
                        exid: ex.id,
                        aid: aid
                    }, function()
                    {
                        dlg.dialog( 'close' );
                    } );
                },
                'Cancel': function()
                {
                    $( this ).dialog( 'close' );
                },
            },
            close: function()
            {
                dlg.remove();
            },
            open: function()
            {
                select( 0 );
            }
        } );
    }
}
