/**
 * Created by Benny on 24.04.2015.
 */

"use strict";

var TB = TB || {}

// Inter/IFrame Communication
TB.ICom =  {

    callbacks :  {},

    init : function() {

        if ( TB.Env.isNativeMobile() ) {

            window.onmessage = function( e ) {
                var d = e.data;
                if ( typeof d === "object" && d.hasOwnProperty( 'iComEvent' ) ) {
                    TB.ICom.processEvent( d );
                }
            };

            // Notify app that client is successfully loaded
            TB.ICom.post( 'clientLoaded' );

            /*
            window.onmessage = function(e) {
                //alert( e );
                //alert( e.data );
                TB.Ext.Push.REG_ID = e.data.deviceId;
                //alert( TB.Ext.Push.REG_ID );
            };

            window.top.postMessage({
                'event' : 'getDeviceId'
            }, "*");

            */
        }

    },

    /**
     * Process IComEvent
     *
     * @param Object event iComEvent { iComEvent : {String}, data : {Object}, cbId : {Integer} }
     */
    processEvent : function( event ) {

        // Process known events
        switch( event.iComEvent ) {
            case 'init':
                TB.Env.setPlatform( event.data.platform );
            break;
            case 'setDeviceId':
                TB.Ext.Push.setDeviceId( event.data.deviceId );
            break;
            case 'callback':
                var data = event.data;
                if ( data.cbId &&
                    TB.ICom.callbacks.hasOwnProperty( data.cbId ) &&
                    typeof TB.ICom.callbacks[ data.cbId ] === "function" ) {

                    TB.ICom.callbacks[ data.cbId ]( data );
                    delete TB.ICom.callbacks[ data.cbId ];
                }
            break;
            case 'pushNotification':
                var pd = TB.Controller.getPageDataFromUrl();
                if ( pd && pd.c && "News" == pd.c ) {
                    TB.Controller.reload();
                } else {
                    TB.Controller.do( 'News' );
                }
            break;
        }

    },

    post : function( eventName, data, cb ) {

        var iComEvent = {
            iComEvent : eventName,
            data : data || null,
            cbId : null
        }, uid = null;

        if ( cb && typeof cb === "function" ) {
            uid = '_' + Math.random().toString(36).substr(2, 9);
            TB.ICom.callbacks[ uid ] = cb;
            iComEvent.cbId = uid;
        }

        window.top.postMessage( iComEvent, "*" );
    }
};

