/**
 * (c) by aheadware.com
 */
"use strict";

var app = app || {};
app.core = app.core || {};

/**
 * NotificationManager logic
 */
app.core.NotificationManager = (function()
{
    var isInitiated = false,
        timeoutId = null,
        defaultDelay = 60 * 1000, // 30 secs
        timeoutDuration = defaultDelay,
        $notificationRoot,
        schedule, getNotifications, processNotifications, onClick, markAllAsRead;

    onClick = function()
    {
        var isNew = ( $(this).attr( 'data-notification-is-new' ) === '1' );

        app.core.Rpc.call(
            'Notification',
            'get',
            {
                notificationId : $(this).attr( 'data-notification-id' )
            },
            function( res )
            {
                var n = new app.model.Notification( res.notification ),
                    actionUrl = n.getActionUrl();

                if ( actionUrl )
                {
                    app.core.NotificationManager.forceUpdate();
                    if ( isNew && n.isForceReload() )
                    {
                        app.core.App.setConfig( 'version', 1 );
                    }
                    app.core.Controller.redirect( actionUrl );
                }
                else
                {
                    app.gui.PageLoader.hide();
                }
            },
            function()
            {
                app.gui.PageLoader.hide();
            }
        );
    };

    markAllAsRead = function()
    {
        app.gui.PageLoader.show();
        app.core.Rpc.call(
            'Notification',
            'markAllAsRead',
            null,
            function (res) {
                app.core.NotificationManager.forceUpdate();
                app.gui.PageLoader.hide();
            }
        );
    };

    processNotifications = function( notificationData, timestamps )
    {
        var lastNotificationUpdate = app.util.Helper.getUnixTimeStampFromUTCTime( timestamps.last_notification_update_dt ),
            notifications = [],
            n = null,
            notificationCreated;

        if ( notificationData && notificationData.length > 0  )
        {
            for ( var ni = 0; ni < notificationData.length; ni++ )
            {
                n = new app.model.Notification( notificationData[ ni ] );
                notifications.push( n );
            }
        }

        app.gui.Navbar.setNotificationDropdown( notifications );
    };

    getNotifications = function()
    {
        clearTimeout( timeoutId );

        app.core.Rpc.call(
            'Notification',
            'get',
            null,
            function( res )
            {
                if ( res && res.hasOwnProperty( 'notifications' ) && res.hasOwnProperty( 'profile_timestamps' ) )
                {
                    try
                    {
                        processNotifications( res.notifications, res.profile_timestamps );
                    }
                    catch( e )
                    {
                        // Fail silently
                    }
                }
                timeoutDuration = defaultDelay;
                schedule();
            }
            ,
            function()
            {
                // No error handling
                timeoutDuration += defaultDelay;
                schedule();
            }
        );
    };

    schedule = function( delay )
    {
        timeoutId = setTimeout( getNotifications, delay || timeoutDuration );
    };

    return {
        destroy : function()
        {
            clearTimeout( timeoutId );
            timeoutId = null;
        }
        ,
        init : function()
        {
            // only initiate once
            if ( null !== timeoutId ) return;

            // During initialisation, the scheduler is pretty fast
            schedule( 3000 );
        }
        ,
        initHandlers : function()
        {
            $notificationRoot = $( 'nav' ).first();;
            $notificationRoot.off( 'click', '[data-type="notification-item"]', onClick );
            $notificationRoot.on( 'click', '[data-type="notification-item"]', onClick );
            $notificationRoot.off( 'click', '[data-id="btn-mark-all-notifications-as-read"]', markAllAsRead );
            $notificationRoot.on( 'click', '[data-id="btn-mark-all-notifications-as-read"]', markAllAsRead );
        }
        ,
        forceUpdate : function()
        {
            getNotifications();
        }
    };
})();