/******************************************************************************\
 *
 *      View Box tracking functions
 *
\******************************************************************************/

viewDataHistory = [];
viewDataOld = {};

var viewTracker = function()
{
    var markViewData  = $( '.pianos4_mark  > .pianos4_view_canvas > svg' )[ 0 ].viewBox.baseVal;
    if( pianos.getParams().phase === "comparison" )
        var printViewData = $( '.pianos4_print > .pianos4_view_canvas > svg' )[ 0 ].viewBox.baseVal;
    
    var projectViewData = function( indata, rot )
    {
        return {
            TL: rotateAround( [ indata.x,                indata.y                 ], rot ),
            TR: rotateAround( [ indata.x + indata.width, indata.y                 ], rot ),
            BL: rotateAround( [ indata.x,                indata.y + indata.height ], rot ),
            BR: rotateAround( [ indata.x + indata.width, indata.y + indata.height ], rot )
        };
    }
    
    var viewData = {
        time: Date.now(),
        nb:   1,
        mark: projectViewData( markViewData, rotationView.mark ),
    }
    
    if( pianos.getParams().phase === "comparison" )
        viewData.print = projectViewData( printViewData, rotationView.print );
    
    var sameviewpoint = JSON.stringify( viewData.mark ) === JSON.stringify( viewDataOld.mark );
    if( pianos.getParams().phase === "comparison" )
        sameviewpoint = sameviewpoint & ( JSON.stringify( viewData.print ) === JSON.stringify( viewDataOld.print ) );
    
    if( Object.keys( viewDataOld ).length == 0 )
    {
        viewDataOld = viewData;
    } else if( sameviewpoint )
    {
        if( pianosfocus )
            viewDataOld.nb = viewDataOld.nb + 1;
    } else {
        viewDataHistory.push( viewDataOld );
        log( "New viewBox pushed to the history (" + viewDataHistory.length + " positions stored)" );
        viewDataOld = viewData;
    }
}

/******************************************************************************\
 *
 *      Mouse position and current focus (mark or print) tracking functions
 *
\******************************************************************************/

currentFocus = null;
mouseLocation = null;

mouseHistory = []
mouseLocationCorrectedOld = {};

$( document ).ready( function()
{
    setTimeout( function()
    {
        $( document ).mousemove( function( event )
        {
            mouseLocation = [ event.pageX, event.pageY ];
        } );
        $( '.pianos4_mark' ).mouseover( function( event )
        {
            currentFocus = "mark";
        } );
        $( '.pianos4_mark' ).mouseout( function( event )
        {
            currentFocus = null;
        } );
        $( '.pianos4_print' ).mouseover( function( event )
        {
            currentFocus = "print";
        } );
        $( '.pianos4_print' ).mouseout( function( event )
        {
            currentFocus = null;
        } );
    }, 0 );
} );

var mouseTracker = function()
{
    var p = null;
    
    if( currentFocus != null )
    {
        p = pianos.getViewsdict()[ currentFocus ].getCanvasPos( mouseLocation );
        p = rotateAround( p, rotationView[ currentFocus ] );
        
        var mouseLocationCorrected = {
            time: Date.now(),
            nb: 1,
            focus: currentFocus,
            pos: p
        };
        
        if( Object.keys( mouseLocationCorrectedOld ).length == 0 )
        {
            mouseLocationCorrectedOld = mouseLocationCorrected;
        } else if( mouseLocationCorrected.focus    == mouseLocationCorrectedOld.focus    &&
                   mouseLocationCorrected.pos[ 0 ] == mouseLocationCorrectedOld.pos[ 0 ] &&
                   mouseLocationCorrected.pos[ 1 ] == mouseLocationCorrectedOld.pos[ 1 ] )
        {
            mouseLocationCorrectedOld.nb = mouseLocationCorrectedOld.nb + 1;
        } else {
            mouseHistory.push( mouseLocationCorrectedOld );
            log( "New mouse position pushed to the history (" + mouseHistory.length + " positions stored)" );
            mouseLocationCorrectedOld = mouseLocationCorrected;
        }
    } else {
        if( Object.keys( mouseLocationCorrectedOld ).length != 0 )
        {
            mouseHistory.push( mouseLocationCorrectedOld );
            mouseLocationCorrectedOld = {};
            log( "New mouse position pushed to the history (" + mouseHistory.length + " positions stored) (out of focus)" );
        }
    }
}

/******************************************************************************\
*
*      Save to db
*
\******************************************************************************/

var saveTrackerData = function()
{
    if( viewDataHistory.length != 0 )
    {
        var params = pianos.getParams();
        
        $.ajax( {
            url: '?action=rpc&method=saveUserTrack',
            
            type: "POST",
            dataType: 'json',
            
            data: {
                exid:   params.exid,
                userid: params.user.id,
                step:   params.phase == "analysis" ? 1 : 2,
                type:   1,
                data:   JSON.stringify( viewDataHistory )
            },
             
            success: function( data )
            {
                if( ! data.error )
                {
                    log( "viewDataHistory saved to DB" );
                    viewDataHistory = [];
                } else {
                    log( "Error while saving viewDataHistory to DB - Retrying later" );
                }
            },
            error: function()
            {
                log( "Error while saving viewDataHistory to DB - Retrying later" );
            }
        } );
    }
    
    if( mouseHistory.length != 0 )
    {
        var params = pianos.getParams();
        
        $.ajax( {
            url: '?action=rpc&method=saveUserTrack',
            
            type: "POST",
            dataType: 'json',
            
            data: {
                exid:   params.exid,
                userid: params.user.id,
                step:   params.phase == "analysis" ? 1 : 2,
                type:   2,
                data:   JSON.stringify( mouseHistory )
            },
             
            success: function( data )
            {
                if( ! data.error )
                {
                    log( "mouseHistory saved to DB" );
                    mouseHistory = [];
                } else {
                    log( "Error while saving mouseHistory to DB - Retrying later" );
                }
            },
            error: function()
            {
                log( "Error while saving mouseHistory to DB - Retrying later" );
            }
        } );
    }
}

/******************************************************************************\
*
*      PiAnoS focus
*
\******************************************************************************/

pianosfocus = null;

$( document ).ready(
    setTimeout( function()
    {
        $( document ).mouseover( function()
        {
            pianosfocus = true;
        } );
    }, 0 )
);
$( document ).ready(
    setTimeout( function()
    {
        $( document ).mouseout( function()
        {
            pianosfocus = false;
        } );
    }, 0 )
);

/******************************************************************************\
*
*      Timing definition
*
\******************************************************************************/

setInterval( viewTracker, 1000 );
setInterval( mouseTracker, 1000 );
setInterval( saveTrackerData, 20000 );
