/*
 * 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.getOrCreateStateCookie = function()
{
    var value = $.cookie( 'pianos4_backend_state' );
    if( !value )
    {
        value = {
            'tree': {
                'pgroups': {},
                'folders': {}
            },
            'layout': {
                'west': 200
            },
            'imageman': {
                'page': 25
            }
        };
        Pianos4Backend.saveStateCookie( value );
    } else
        value = JSON.parse( value );
    return value;
}

Pianos4Backend.saveStateCookie = function( value )
{
    $.cookie( 'pianos4_backend_state', JSON.stringify( value ) );
}

Pianos4Backend.IFrame = function( selector, id, isExID, comparison )
{
    assert( selector !== null );
    
    this.init = function()
    {
        var url = '?action=report&' + ( isExID ? 'id=' : 'aid=' ) + id;
        if( comparison )
            url += '&step=COMPARISON';
        var node = new udb.node( {
            element: selector
        } );
        node.dom().css( 'width', '100%' ).css( 'height', '100%' );
        _iframe = new udb.iframe( {
            src: url,
            parent: node,
            onLoad: function()
            {
                var div = _iframe.dom( true );
                
            }
        } );
        _iframe.dom().css( 'width', '100%' ).css( 'height', '100%' );
    }

    var _iframe = null;
    var _div = null;
}

Pianos4Backend.showFormDialog = function( opts, modal )
{
    var form = $( '<form />' );
    for( var i in opts.fields )
    {
        var f = opts.fields[ i ];
        
        if( f.type == 'text' || f.type == 'password' || f.type == 'checkbox' )
        {
            var id = f.name + '_' + ( new Date().getTime() );
            var label = $( '<label />' ).text( f.label ).attr( 'for', id );
            var input = $( '<input />' ).attr( 'type', f.type ).attr( 'id', id ).attr( 'name', f.name );
            if( f.value )
                input.attr( 'value', f.value );
            if( f.disabled )
                input.prop( 'disabled', true );
            if( f.type == 'checkbox' && f.checked )
                input.prop( 'checked', true );
            form.append( $( '<div />' ).append( label ).append( input ) );
        } else if( f.type == 'select' )
        {
            assert( 'values' in f );
            var id = f.name + '_' + ( new Date().getTime() );
            var label = $( '<label />' ).text( f.label ).attr( 'for', id );
            var select = $( '<select />' ).attr( 'name', f.name );
            for( var j in f.values )
            {
                var opt = f.values[ j ];
                var domopt = $( '<option />' ).attr( 'value', opt.id ).text( opt.name );
                if( typeof ( f.value ) != 'undefined' && f.value == opt.id )
                    domopt.prop( 'selected', true );
                domopt.appendTo( select );
            }
            form.append( $( '<div />' ).append( label ).append( select ) );
        } else if( f.type == 'static' )
        {
            form.append( $( '<div />' ).text( f.label ) );
        } else if( f.type == 'dom' )
        {
            form.append( f.content );
        } else if( f.type == 'textarea' )
        {
            var id = f.name + '_' + ( new Date().getTime() );
            var label = $( '<label />' ).text( f.label ).attr( 'for', id );
            var area = $( '<textarea />' ).attr( 'id', id ).attr( 'name', f.name ).attr( 'rows', 10 ).attr( 'cols', 35 );
            if( f.value )
                area.text( f.value );
            form.append( $( '<div />' ).append( label ).append( area ) );
        } else
        {
            assert( false );
        }
        
        if( !( 'constraints' in f ) )
        {
            f.constraints = {};
        } else if( $.isArray( f.constraints ) )
        {
            var constraints = {};
            for( var i in f.constraints )
                constraints[ f.constraints[ i ] ] = true;
            f.constraints = constraints;
        }
    }
    
    var errors = $( '<div />' );
    
    $( '<div />' ).addClass( 'aligned_form' ).append( form ).append( errors ).dialog( {
        title: opts.title,
        width: 310,
        modal: modal,
        buttons: {
            'OK': function()
            {
                var data = form.serializeObject();
                errors.html( '' );
                for( var i in opts.fields )
                {
                    var f = opts.fields[ i ];
                    if( 'not-empty' in f.constraints && ( !( f.name in data ) || data[ f.name ].length == 0 ) )
                        errors.append( $( '<div />' ).addClass( 'ui-state-error' ).text( f.label + ' cannot be empty' ) );
                    if( f.name in data && 'must-match' in f.constraints && f.constraints[ 'must-match' ][ 0 ] in data && data[ f.constraints[ 'must-match' ][ 0 ] ] != data[ f.name ] )
                        errors.append( $( '<div />' ).addClass( 'ui-state-error' ).text( f.constraints[ 'must-match' ][ 1 ] ) );
                }
                if( errors.find( '*' ).size() )
                    return;
                $( this ).dialog( 'close' ).remove();
                opts.ok( data );
            },
            'Cancel': function()
            {
                $( this ).dialog( 'close' ).remove();
            },
        },
    } );
}


Pianos4Backend.ImageManagerDropzones = function()
{
    Dropzone.autoDiscover = false;
    
    var uploader = $( '<div />' )
        .css( 'display', 'grid' )
        .css( 'grid-template-columns', '1fr 1fr' )
        .css( 'grid-gap', '5px' )
        .css( 'height', 'calc(100% - 20px)' )
        .css( 'width', '100%' )
        .css( 'padding-top', '20px' );
    
    $( '<div />' )
        .attr( 'class', 'dropzonediv' )
        .append( $( '<div />' )
            .attr( 'class', 'dropzonetitle' )
            .text( 'Mark' )
        )
        .append( $( '<div />' )
            .attr( 'id', 'dropzonedivmark' )
            .attr( 'class', 'dropzone' )
            .dropzone( {
                url: "?action=upload_image2" ,
                params: {
                    type: 'MARK'
                },
                dictDefaultMessage: "Drag and drop new marks here",
            } )
            .on( "drop", function( event )
            {
                $( '#dropzonedivmark > div.dz-message' ).remove()
            } )
        )
        .appendTo( uploader );
    
    $( '<div />' )
        .attr( 'class', 'dropzonediv' )
        .append( $( '<div />' )
            .attr( 'class', 'dropzonetitle' )
            .text( 'Print' )
        )
        .append( $( '<div />' )
            .attr( 'id', 'dropzonedivprint' )
            .attr( 'class', 'dropzone' )
            .dropzone( {
                url: "?action=upload_image2" ,
                params: {
                    type: 'PRINT'
                },
                dictDefaultMessage: "Drag and drop new prints here",
            } )
            .on( "drop", function( event )
            {
                $( '#dropzonedivprint > div.dz-message' ).remove()
            } )
        )
        .appendTo( uploader );
    
    var dlgopts = {
        autoOpen: true,
        modal: true,
        width: $( window ).width() * 0.7,
        height: $( window ).height() * 0.7,
        resizable: true,
        title: "Upload multiple images as mark or print",
        buttons: {
            'Close': function()
            {
                $( this ).dialog( 'close' );
                location.reload(); 
            },
        }
    }
    
    $( '<div />' )
        .attr( 'id', 'dropzonedlg' )
        .addClass( 'pianos4_dialog' )
        .append( uploader )
        .dialog( dlgopts );
}
