// Constants
const CLIENT_ID = 'testApp';

// Server endpoints
const API_URL = 'https://BREEZE-FQDN/services/UnifiedAgentController/UACAPI';
const BROADCAST_URL = 'https://BREEZE-FQDN/services/Broadcast-UnifiedAgentController/broadcast';

// Get Auth info
var SSOToken = $.cookie('UACCookieSession');
var tokenData = SSOToken && parseSSOToken(SSOToken);

// UAC Configuration for Avaya Customer Services SDK
var config = {
    uacConfiguration: new AvayaCustomerServices.Config.UACConfiguration({
        enabled: true,
        clientInfo: { id: CLIENT_ID },
        serverInfo: { apiUrl: API_URL },
        notificationInfo: { broadcastUrl: BROADCAST_URL },
        authenticationInfo: { enabled: true, tokens: ['Authorization'] }
    })
};
// Bootstrap Customer Interaction Services SDK
var client = new AvayaCustomerServices(config);
var clientSession = client.createClientSession();


var computed = {
    interactionCollection: function () {
        return this.interactions._collection;
    },
    workRequestCollection: function () {
        return this.workRequests._collection;
    }
};

var methods = {
    getMessages: function (interaction) {
        var messages = [];
        var media = interaction.getInteractionMedia();
        if (media && media.messages.length) {
            for(var i = 0; i < media.messages.length; i++) {
                messages.push({
                    content: media.messages[i].body,
                    isSelf: media.messages[i].receivedFrom.isSelf,
                    from: media.messages[i].receivedFrom.participantName,
                    created: new Date(media.messages[i].arrivalDate)
                });
            }
        }
        var chats = document.getElementsByClassName('chat-history');
        if (chats.length) {
            for (var j = 0; j < chats.length; j++) {
                chats[j].scrollTop = chats[j].scrollHeight;
            }
        }
        return messages;
    },
    sendMessage: function(interaction) {
        var media = interaction.getInteractionMedia();
        if (media && this.messageContent) {
            media.send(this.messageContent);
        }
        this.messageContent = "";
        return false;
    }
}

var vue = new Vue({
    el: '#appContainer',
    components: {
        'tabset': VueStrap.tabset,
        'tab': VueStrap.tab,
        'v-select': VueStrap.select,
        'v-option': VueStrap.option
    },
    data: {
        user: {userProfileDetailsList: []},
        agent: {},
        interactions: {},
        workRequests: {},
        work: {},
        credentials: {},
        token: '',
        interactionAddress: '',
        profileId: [],
    },
    computed: computed,
    methods: methods
});

// Start session
SSOToken && start();

function start () {
    
    vue.token = {
        header: 'Authorization',
        value: SSOToken
    };

    clientSession.setToken(vue.token);
    clientSession.start();
    
    // Get configuration
    clientSession.getConfiguration(tokenData.authHandle).then(function(user) {
        user.profileList = [];
        for (var i = 0, len = user.userProfileDetailsList.length; i < len; i++) {
            user.profileList.push({
                value: user.userProfileDetailsList[i].userProfile.id,
                label: user.userProfileDetailsList[i].userProfile.profileName
            });
        }
        vue.user = user;
    });

    vue.agent = clientSession.createAgent();
    vue.work = clientSession.createWork();
    vue.interactions = vue.work.getInteractions();
    vue.workRequests = vue.work.getWorkRequests();
    
    // Attach listener for agent deactivate event
    vue.agent.addOnDeactivatedCallback(function () {
        $.cookie('UACCookieSession', '', { expires: -1, path: '/' });
        window.location.reload();
    });
}

/**
 * Parse JSON Web Token
 *
 * @private
 * @returns {Object}
 */
function parseSSOToken(token) {
    var parsedJWT;
    var encodedJWT = token.split(' ')[1];
    if (!encodedJWT) return;

    var payload = encodedJWT.split('.')[1];
    if (!payload) return;

    try {
        parsedJWT = JSON.parse(window.atob(payload));
    } catch(error) {
        parsedJWT = {};
    }
    return {
        authHandle: parsedJWT.sub,
        expires: parsedJWT.exp
    };
}
