/**
 * Copyright 2018 Avaya Inc. All Rights Reserved.
 *
 * Usage of this source is bound to the terms described in
 * licences/License.txt
 *
 * Avaya - Confidential & Proprietary. Use pursuant to your signed agreement or
 * Avaya Policy
 * 
 * A self-contained file to create a widget with WebChat testing tools.
 * Embed into the HTML of the chat page to use it.
 */

(function (chatTest, avayaGlobal, chatConfig, chatUI, webChat, jQuery) {
    "use strict";

    // localStorage key for saving/loading details
    var itemKey = "mockUserDetails";

    // Messaging styling demo: Default names and messages
    var defaultAgentName = 'N. Bison';
    var defaultCustName = 'M. Smith';
    var defaultBotName = 'Chatbot';
    var customerMessage = 'This is a customer message. You can edit the style by changing the p.sent entry in style.css. This is a test. Don\'t try using regex to parse HTML! Messages should wrap around. I think this is working.';
    var customerMessageExplainer = 'Testing customer messages next. Customer messages require a WebSocket to be opened, so the console will throw an exception about "webSocket is undefined". This is expected';
    var systemMessageExplainer = 'This is a system message. The style for this message type is defined by the p.system entry in style.css';
    var agentDateMessageExplainer = 'Agent timestamps use the p.agentDate class. This results in them being right-aligned in bold italics';
    var webOnHoldMessageExplainer = 'Web-On-Hold messages and URLs are treated as system messages. If you want them to appear as agent messages, edit the playWebOnHoldMessages method inside webChat.js';
    var chatBotExplainer = 'Testing a chatbot message next. The actual name would be assigned when the chatbot joins the room; to change the name, you need to configure AutomationController in System Manager to use a different name';

    // chat load testing details. Change the delay parameter to e.g. 2000 to send every two seconds
    var numberSent = 0;
    var delay = 1000;
    var isTypingDelay = 500; // defines how often to send isTyping messages (e.g. every half a second by default)
    var interval;
    var isTypingInterval;

    // by default, these will be sent every tenth message
    var urlFrequency = 10;
    var url = 'http://example.com/';

    // identifies the widget
    var divId = 'chatTestDiv';

    /**
     *	Save the user's details to localStorage.
     */
    function saveDetails() {
        var details = {
            "firstName": avayaGlobal.getEl("user-chat").value,
            "lastName": avayaGlobal.getEl("user-chat-last").value,
            "email": avayaGlobal.getEl("email-chat").value,
            "phoneCountry": avayaGlobal.getEl("phone-country").value,
            "phoneArea": avayaGlobal.getEl("phone-area").value,
            "phoneNumber": avayaGlobal.getEl("phone-chat").value
        };
        localStorage.setItem(itemKey, JSON.stringify(details));
        alert("Details have been saved to localStorage");
    }


    /**
     *	Load the details and write them into the various fields.
     */
    function loadDetails() {
        var details = JSON.parse(localStorage.getItem(itemKey));
        avayaGlobal.getEl("user-chat").value = details.firstName;
        avayaGlobal.getEl("user-chat-last").value = details.lastName;
        avayaGlobal.getEl("email-chat").value = details.email;
        avayaGlobal.getEl("phone-country").value = details.phoneCountry;
        avayaGlobal.getEl("phone-area").value = details.phoneArea;
        avayaGlobal.getEl("phone-chat").value = details.phoneNumber;
    }


    /**
     * Create a mock transcript to show the different styles.
     * Note: in this, we only use a single name field. This is because the display name (what is shown in the transcript)
     * defaults to a combination of the firstName and lastName fields when the chat is approved.
     */
    function createMockTranscript() {
        var agentName = window.prompt("What is the agent's name? Default is " + defaultAgentName);
        var custName = window.prompt("What is the customer's name? Default is " + defaultCustName);
        var botName = window.prompt("What is the chatbot's display name? Default is " + defaultBotName);

        if (agentName.trim() === '') {
            agentName = defaultAgentName;
        }
        if (custName.trim() === '') {
            custName = defaultCustName;
        }
        if (botName.trim() === '') {
            botName = defaultBotName;
        }

        webChat.g_user = custName;
        webChat.chatBotName = botName;

        console.log('createMockTranscript: names are set up. Testing');

        // open UI panel
        chatUI.changeToChatMode();

        // test system message
        webChat.writeResponse(systemMessageExplainer, chatConfig.writeResponseClassSystem);
        webChat.writeResponse(agentDateMessageExplainer, chatConfig.writeResponseClassSystem);
        webChat.writeResponse(webOnHoldMessageExplainer, chatConfig.writeResponseClassSystem);

        // send an agent message. In this case, I am skipping the low-level handleMessage() method in webChatSocket.js
        var date = new Date().valueOf();
        var agentChatMessage = {'method': 'newMessage', 'message': 'Testing agent chat message. This uses the p.response class', 'displayName': agentName, 'timestamp': date - 9000};
        webChat.notifyNewMessage(agentChatMessage);

        // simulate a page push message
        var pagePushMessage = {'method': 'newPushPageMessage', 'displayName': agentName, 'pagePushURL': 'https://confluence.forge.avaya.com/display/OCPROVIDER/Customer+WebSocket+API#CustomerWebSocketAPI-PagePushNotification', 'pagePushDestination': 'newTab', 'timestamp': date - 7000};
        webChat.notifyNewPagePushMessage(pagePushMessage);

        // test chatbot
        webChat.writeResponse(chatBotExplainer, chatConfig.writeResponseClassSystem);
        var chatBotMessage = {'method': 'newMessage', 'message': 'Testing chatbot message. If you want to change the style, edit the p.chatbot entry in style.css', 'displayName': webChat.chatBotName, 'timestamp': date - 5000};
        webChat.notifyNewMessage(chatBotMessage);

        // simulate a customer chat message. The second line will throw a TypeError about "webSocket is undefined" - this is expected.
        webChat.writeResponse(customerMessageExplainer, chatConfig.writeResponseClassSystem);
        webChat.outMessage.value = customerMessage;
        webChat.sendChatMessage();
    }

    function stopSendingMessages() {
        clearInterval(interval);
        clearInterval(isTypingInterval);
    }

    /**
     * Start sending the word "Testing" once a second. The chat *MUST* be opened first.
     */
    function startSendingMessages() {
        if (webChat.initCalled) {
            interval = setInterval(function () {

                numberSent++;
                if (numberSent > 0 && (numberSent % urlFrequency) === 0) {
                    webChat.outMessage.value = 'Testing ' + url + ' ' + numberSent;
                } else {
                    webChat.outMessage.value = 'Testing ' + numberSent;
                }

                webChat.sendChatMessage();
            }, delay);

            isTypingInterval = setInterval(function () {
                webChat.startTypingTimer();
            }, isTypingDelay);

        } else {
            alert("Wait until the chat is opened first!");
            return;
        }
    }

    function createWidget() {
        var widget = document.createElement("div");
        widget.id = divId;
        widget.title = "Avaya WebChat Testing Tools";
        
        // make it clear that this is not for production use
        var span = document.createElement("span");
        span.textContent = "WARNING! This is NOT for production use!";
        span.style.font = "14px bold";
        span.style.fontFamily = "Arial, san-serif;";
        span.style.padding = "5px;";
        widget.appendChild(span);

        // create and add the required buttons
        widget.appendChild(createButton("Save user details", saveDetails));
        widget.appendChild(createButton("Load user details", loadDetails));
        widget.appendChild(createButton("Create mock transcript", createMockTranscript));
        widget.appendChild(createButton("Start sending messages", startSendingMessages));
        widget.appendChild(createButton("Stop sending messages", stopSendingMessages));

        document.body.appendChild(widget);

        // place the widget 100 pixels left of the window edge, and about a quarter of the way down
        jQuery('#' + divId).dialog({
            position: {my: "left top", at: "left+100 top+25%", of: window}
        });
        jQuery('#' + divId + " > button").button();
    }

    function createButton(title, clickMethod) {
        var newButton = document.createElement("button");
        newButton.class = "button ui-button ui-corner-all ui-widget";
        newButton.style.width = "100%";
        newButton.textContent = title;
        newButton.addEventListener('click', clickMethod);
        return newButton;
    }



    function setup() {
        if (webChat && chatUI && jQuery) {
            createWidget();
        } else {
            console.error("This script requires jQuery and the Avaya WebChat files!");
        }
    }

    setTimeout(setup, 0);

    return chatTest;
})(window.chatTest = window.chatTest || {}, window.avayaGlobal, window.chatConfig, window.chatUI, window.webChat, window.jQuery);