/**
 * (c) by aheadware.com
 */

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

app.util.OneSignal = (function(){

    var OneSignal,
        cbNotificationOpened,
        cbGetIds;

    /**
     * Retrieve notification jsonData once user clicked on it
     * @param jsonData
     */
    cbNotificationOpened = function( jsonData )
    {
        if ( jsonData &&
            jsonData.notification &&
            jsonData.notification.payload &&
            jsonData.notification.payload.additionalData )
        {
            var addData = jsonData.notification.payload.additionalData;

            if ( addData && addData.hasOwnProperty( 'inAppUrl' ) )
            {
                app.core.Controller.redirect( addData.inAppUrl );
            }
        }
        app.core.NotificationManager.forceUpdate();
    };

    /**
     * Retrieve one signal player id
     * @param playerId
     */
    cbGetIds = function( ids )
    {

        app.core.Rpc.call(
            'Account',
            'registerDevice',
            {
                platform : 'ANDROID',
                reg_id : ids.userId
            },
            function()
            {
                OneSignal.setSubscription( true );
            }
            ,
            function( err )
            {
                //console.log( "OneSignal Error", err );
            }
        );
    };

    return {
        init : function()
        {
            if ( !window.plugins || !window.plugins.OneSignal ) return;

            OneSignal = window.plugins.OneSignal;

            var appId = app.core.App.getConfig( 'onesignal.appId' );

            if ( appId && app.util.Environment.isNativeMobile() && app.core.Session.isLoggedIn() )
            {
                try
                {
                    OneSignal.setLocationShared( false );
                }
                catch( e )
                {
                    // fail silently
                }
                
                OneSignal
                    .startInit( appId )
                    .handleNotificationOpened( cbNotificationOpened )
                    .endInit();

                OneSignal.getIds( cbGetIds );
            }
        }
        ,
        destroy : function()
        {
            if ( !window.plugins || !window.plugins.OneSignal ) return;

            OneSignal.setSubscription( false );
        }
    }

})();