/* global AvayaCoBrowseClientServices, $LAB, Android */

/**
 * @license coBrowse.js<br>
 * Copyright 2015 Avaya Inc. All Rights Reserved.<br>
 * <br>
 * Usage of this source is bound to the terms described in licences/License.txt<br>
 * <br>
 * Avaya - Confidential & Proprietary. <br>
 * Use pursuant to your signed agreement or Avaya Policy
 */

var coBrowse = {
    coBrowseInstance: null,
    isSecure: false,
    isPaused: false,
    hostName: "",
    userName: "",
    coBrowseKey: "",
    loadDependencies: function (hostName, userName, coBrowseKey) {
        'use strict';

        var coBrowseSDKPath = 'js/libs/cobrowse/';

        $LAB.script(coBrowseSDKPath + 'sock.js')
                .script(coBrowseSDKPath + 'Base64.js').script(
                coBrowseSDKPath + 'md5.js').script(
                coBrowseSDKPath + 'jquery_path.js').script(
                coBrowseSDKPath + 'AvayaCoBrowseClientServices.min.js')
                .wait(function () {
                    coBrowse.init(hostName, userName, coBrowseKey);
                });
    },
    init: function (hostName, userName, coBrowseKey) {
        'use strict';

        this.hostName = hostName;
        this.userName = userName;
        this.coBrowseKey = coBrowseKey;

        var config = new AvayaCoBrowseClientServices.Config.CoBrowseConfiguration();
        console.info('AVCOBROWSE Engine (Customer) Load Complete');
        console.info('[jQuery]: ' + $().jquery);
        config.serverInfo.hostName = this.hostName;
        config.serverInfo.port = this.isSecure ? '443' : '80';
        config.serverInfo.isSecure = this.isSecure;
        config.enabled = true;

        var coBrowseCustomerClientService = new AvayaCoBrowseClientServices();
        coBrowseCustomerClientService.registerLogger(window.console);

        try {
            this.coBrowseInstance = coBrowseCustomerClientService
                    .createCustomerCobrowse(config);

            if (this.coBrowseInstance) {
                console.info('Successfully Initilized');
                this.coBrowseInstance.addElementIDToRemove('chatPanel');
                this.coBrowseInstance.addElementIDToRemove('hidePauseStop');
                this.coBrowseInstance
                        .addElementIDToRemove('hideRequestControl');
                this.registerAPICallbacks();
                this.coBrowseInstance.start();
                this.joinSession(
                        this.userName,
                        this.coBrowseKey);
            }
        } catch (e) {
            console.log(e);
        }
    },
    registerAPICallbacks: function () { // NOSONAR cannot be simplified any further
        'use strict';

        var instance = this.coBrowseInstance;

        instance.addOnConnectionResetCallback(function (evt) {
            console.error('addOnConnectionResetCallback is unimplemented!');
        });

        instance.addOnConnectionCallback(function (evt) {
            console.info('Connected to Co-Browse with ' + evt.agent);
			window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onConnection"});
			});

        instance.addOnConnectionFailureCallback(function (evt) {
            console.info('Failed to connect to Co-Browse ' + evt.msg);
        });

        instance.addOnSessionCloseCallback(function (evt) {
            console.info('Co-Browse session closed.');
            
            var str = evt.msg.split(':');
            var title = '';
            var text = '';

            if (str.length > 0) {
                if (str[0] === 'inactive_timeout') {
                    title = 'Inactive Session by Agent';
                } else if (str[0] === 'session_timeout') {
                    title = 'Session Timeout by System';
                } else {
                    title = 'Session Closed by the Agent';
                }

                text = str[1];
            }
window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onSessionClose",messageTitle: title, messageText: text});
           
        });

        instance.addOnControlRequestCallback(function (evt) {
            console.info('Received Control request from ' + evt.agent);
            window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onControlRequest"});
            
        });

        instance.addOnControlReleaseCallback(function (evt) {
            console.info('Agent ' + evt.agent + ' has released Control.');
            window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onControlRelease"});
          
        });

        instance.addOnfireInactivityCallback(function (evt) {
            console.error('addOnfireInactivityCallback is unimplemented!');
        });

        instance.addOnStopInactivityTimerCallback(function (evt) {
            console.error('addOnStopInactivityTimerCallback is unimplemented!');
        });
    },
    joinSession: function (name, sessionKey) {
        'use strict';

        if (name === '') {
            name = 'Customer';
        }

        this.coBrowseInstance.joinSession(name, sessionKey).then(
                this.onJoinSuccess.bind(this), this.onJoinFailure);
    },
    stopSession: function () {
        'use strict';

        console.info('Attempting to stop the Co-Browse session.');
        this.coBrowseInstance.logoutSession().then(
                this.onStopSuccess.bind(this), this.onStopFailure);
    },
    togglePause: function () {
        'use strict';

        if (this.isPaused === false) {
            console.info('Attempting to pause the Co-Browse session.');
            this.coBrowseInstance.pause().then(this.onPauseSuccess.bind(this),
                    this.onPauseFailure);
        } else {
            console.info('Attempting to resume the Co-Browse session.');
            this.coBrowseInstance.resume().then(
                    this.onResumeSuccess.bind(this), this.onResumeFailure);
        }
    },
    grantControl: function (agent) {
        'use strict';

        console.info('Co-Browse Control request for ' + agent + ' granted.');
        this.coBrowseInstance.grantControl().then(
                this.onGrantControlSuccess.bind(this),
                this.onGrantControlFailure);
    },
    denyControl: function (agent) {
        'use strict';

        console.info('Co-Browse Control request for ' + agent + ' denied.');
        this.coBrowseInstance.denyControl()
                .then(this.onDenyControlSuccess.bind(this),
                        this.onDenyControlFailure);
    },
    revokeControl: function (agent) {
        'use strict';

        console.info('Co-Browse Revoke Control request for ' + agent + ' initiated.');
        this.coBrowseInstance.revokeControl().then(
                this.onRevokeControlSuccess.bind(this),
                this.onRevokeControlFailure);
    },
    onJoinSuccess: function (data) {
        'use strict';

        console.info('Join session successful.');
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onJoinSuccess"});
       
    },
    onJoinFailure: function (error) {
        'use strict';

        console.info('Join session failed ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onJoinFailure"});
        
    },
    onGrantControlSuccess: function (data) {
        'use strict';

        console.info('Grant control successful.');
window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onGrantControlSuccess"});
       
    },
    onGrantControlFailure: function (error) {
        'use strict';

        console.info('Unable to grant control, reason ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onGrantControlFailure"});
        
    },
    onDenyControlSuccess: function (data) {
        'use strict';

        console.info('Deny control successful.');
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onDenyControlSuccess"});
       
    },
    onDenyControlFailure: function (error) {
        'use strict';

        console.info('Unable to deny control, reason ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onDenyControlFailure"});
      
    },
    onRevokeControlSuccess: function (data) {
        'use strict';

        console.info('Revoke control successful.');
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onRevokeControlSuccess"});
        
    },
    onRevokeControlFailure: function (error) {
        'use strict';

        console.info('Unable to revoke control, reason ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onRevokeControlFailure"});
        
    },
    onPauseSuccess: function (data) {
        'use strict';

        console.info('Paused co-browse successfully.');
        this.isPaused = true;
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onPauseSuccess"});
        
    },
    onPauseFailure: function (error) {
        'use strict';

        console.info('Unable to pause co-browse, reason ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onPauseFailure"});
        
    },
    onResumeSuccess: function (data) {
        'use strict';

        console.info('Resumed co-browse successfully.');
        this.isPaused = false;
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onResumeSuccess"});
        
    },
    onResumeFailure: function (error) {
        'use strict';

        console.info('Unable to resume co-browse, reason ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onResumeFailure"});
       
    },
    onStopSuccess: function (data) {
        'use strict';
window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onStopSuccess"});
        
    },
    onStopFailure: function (error) {
        'use strict';

        console.info('Unable to stop co-browse, reason ' + error.getMessage());
        window.webkit.messageHandlers.iOSNotification.postMessage({coBrowseEvent: "onStopFailure"});
      
    }
};
