/*
 * PiAnoS (Picture Annotation System), A fingerprint examiner training tool
 * Copyright (C) 2011-2021 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 Pianos4ToolPan( params )
{
    // ------------------------------
    // Constructor
    // ------------------------------
    
    params = params || {};
    if( !params.phase )
        params.phase = 'comparison';
    
    // ------------------------------
    // Public methods
    // ------------------------------
    
    this.getName = function()
    {
        return 'pan';
    }

    this.getLabel = function()
    {
        return 'Pan';
    }

    this.getIcon = function()
    {
        return 'icons/move.png';
    }

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

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

    this.activate = function()
    {
        log( 'pan tool activate' );
        var views = pianos.getViews();
        for( var i in views )
        {
            var svg = views[ i ].getSVG();
            var g = svg.select( '.pianos4_helpers .pianos4_pan_helpers' );
            if( g.empty() )
            {
                svg.select( '.pianos4_helpers' ).append( 'svg:g' ).classed( 'pianos4_pan_helpers', true );
            } else
            {
                g.attr( 'display', 'inline' );
            }
            svg.classed( 'pianos4_pan_tool_on', true );
        }
    }

    this.deactivate = function()
    {
        log( 'pan tool de-activate' );
        var views = pianos.getViews();
        for( var i in views )
        {
            var svg = views[ i ].getSVG();
            var g = svg.select( '.pianos4_helpers .pianos4_pan_helpers' );
            assert( !g.empty() );
            g.attr( 'display', 'none' );
            svg.classed( 'pianos4_pan_tool_on', false );
        }
    }

    this.onMouseDown = function( pos, target, event )
    {
        if( event.altKey )
        {
            placing = true;
            
            var g = view.getSVG().select( '.pianos4_helpers .pianos4_pan_helpers' );
            assert( !g.empty() );
            
            g.selectAll( '.pianos4_pan_helper' ).remove();
            
            var segs = [
                [
                    [
                        -20.0, 0.0
                    ], [
                        20.0, 0.0
                    ]
                ], [
                    [
                        0.0, -20.0
                    ], [
                        0.0, 20.0
                    ]
                ],
            ];
            
            var sub = g.append( 'svg:g' ).classed( 'pianos4_pan_helper', true ).attr( 'transform', 'translate(' + pos[ 0 ] + ',' + pos[ 1 ] + ')' );
            
            for( var i in segs )
            {
                var s = segs[ i ];
                sub.append( 'svg:line' ).attr( 'x1', s[ 0 ][ 0 ] ).attr( 'x2', s[ 1 ][ 0 ] ).attr( 'y1', s[ 0 ][ 1 ] ).attr( 'y2', s[ 1 ][ 1 ] ).attr( 'opacity', 0.3 ).attr( 'stroke', '#880088' )
                    .attr( 'stroke-width', 4.0 );
                sub.append( 'svg:line' ).attr( 'x1', s[ 0 ][ 0 ] ).attr( 'x2', s[ 1 ][ 0 ] ).attr( 'y1', s[ 0 ][ 1 ] ).attr( 'y2', s[ 1 ][ 1 ] ).attr( 'opacity', 0.3 ).attr( 'stroke', '#dd00dd' )
                    .attr( 'stroke-width', 2.0 );
            }
            
        } else
        {
            var views = pianos.getViews();
            origins = {};
            for( var i in views )
            {
                var v = views[ i ];
                if( !anchored && v.getType() != view.getType() )
                    continue;
                origins[ v.getType() ] = v.getOrigin();
                start = pos;
            }
        }
    }

    this.onMouseMove = function( pos, target )
    {
        if( !placing )
        {
            var offset = [
                start[ 0 ] - pos[ 0 ], start[ 1 ] - pos[ 1 ]
            ];
            var views = pianos.getViews();
            for( var i in views )
            {
                var v = views[ i ];
                if( !anchored && v.getType() != view.getType() )
                    continue;
                var o = [
                    origins[ v.getType() ][ 0 ] + offset[ 0 ], origins[ v.getType() ][ 1 ] + offset[ 1 ]
                ];
                var vb = v.getSVG().attr( 'viewBox' ).split( ' ' );
                vb[ 0 ] = o[ 0 ];
                vb[ 1 ] = o[ 1 ];
                v.getSVG().attr( 'viewBox', vb.join( ' ' ) );
            }
        } else
        {
            var g = view.getSVG().select( '.pianos4_helpers .pianos4_pan_helper' );
            assert( !g.empty() );
            g.attr( 'transform', 'translate(' + pos[ 0 ] + ',' + pos[ 1 ] + ')' );
        }
    }

    this.onMouseUp = function( pos, target )
    {
        if( !placing )
        {
            var offset = [
                start[ 0 ] - pos[ 0 ], start[ 1 ] - pos[ 1 ]
            ];
            var views = pianos.getViews();
            for( var i in views )
            {
                var v = views[ i ];
                if( !anchored && v.getType() != view.getType() )
                    continue;
                var o = [
                    origins[ v.getType() ][ 0 ] + offset[ 0 ], origins[ v.getType() ][ 1 ] + offset[ 1 ]
                ];
                v.setOrigin( o );
            }
            
            start = null;
            origins = null;
        } else
        {
            if( !( view.getType() in anchors ) )
            {
                // Anchor placed in a window that had none
                anchors.length++;
            } else
            {
                // Anchor moved
                if( anchored )
                {
                    options.find( 'input[type=checkbox]' ).removeAttr( 'checked' );
                    setAnchored( false );
                }
            }
            anchors[ view.getType() ] = $.extend( [], true, pos );
            if( anchors.length >= 2 )
            {
                options.find( 'input[type=checkbox]' ).removeAttr( 'disabled' );
                // options.find('div._hint').hide();
                options.find( 'label' ).removeCSS( 'color' );
            }
            placing = false;
        }
        return true;
    }

    this.getOptionsPanel = function()
    {
        if( params.phase == 'analysis' )
            return null;
        
        if( !options )
        {
            var panel = $( '<div class="pianos4_pan_options" />' );
            
            var randomID = 'pianos4_rid_' + ( new Date().getTime() );
            var disabledStr = '';
            var label = $( '<label for="' + randomID + '" />' ).text( 'Bind views' );
            if( anchors.length < 2 )
            {
                disabledStr = ' disabled="disabled"';
                label.css( 'color', '#aaaaaa' );
            }
            var anchoredBox = $( '<input type="checkbox" ' + ( anchored ? 'checked="checked"' : '' ) + ' id="' + randomID + '" ' + disabledStr + '/>' );
            anchoredBox.bind( 'click', function()
            {
                this.blur(); // so that future space+click+drag does not
                                // check/uncheck the box
                setAnchored( this.checked );
            } );
            panel.append( $( '<div />' ).append( anchoredBox ).append( label ) );
            
            panel.append( $( '<div class="_hint" />' ).css( 'margin-top', '0.5em' ).text( 'Place anchors using ' ).append( $( '<strong />' ).text( 'Alt+Click' ) ) );
            
            options = panel;
        }
        
        return options;
    }

    this.getHelp = function()
    {
        return Pianos4Help
            .compile( [
                'Use the pan tool to move the image inside the viewport.',
                'In comparison mode, the two views are not linked and pan independently. You can bind them so that moving one view also moves the other one by the same offset. To make the \'Bind views\' checkbox available, you need to place anchors on both views. Those anchors define points that are deemed to represent the "same" spot. Use the Alt key to place anchors (see below).',
                '<<mouse:left>>: drag to move the view',
                '<<key:space>>: (hold) temporarily switch to the pan tool',
                '<<mouse:middle>>: (shortcut) works like left click, even when the tool is not active',
                '<<key:alt>><<mouse:left>>: place (or move) the anchor',
                'Note: anchors are only visible when the pan tool is active, but the binding is still functional when another tool is active.',
            ] );
    }

    // ------------------------------
    // Private variables
    // ------------------------------
    
    var self = this;
    var view = null;
    var start = null;
    var origins = null;
    var anchors = {
        length: 0
    };
    var anchored = false;
    var placing = false;
    var options = null;
    
    // ------------------------------
    // Private functions
    // ------------------------------
    
    var setAnchored = function( value )
    {
        anchored = value;
        var views = pianos.getViews();
        for( var i in views )
        {
            var v = views[ i ];
            if( anchored )
            {
                v.setCenter( anchors[ v.getType() ] );
                v.setOriginLocked( anchors[ v.getType() ] );
            } else
            {
                v.setOriginLocked( false );
            }
        }
    }
}
