/***********************************************************************
 * Copyright Genesys Laboratories. All Rights Reserved
 ************************************************************************/

/***********************************************************************
 * Widgets Customization Examples IV - Chat and Bot Service sample
 *
 * Base code and page,
 * With Sidebar, Channel Selector, WebChat and TestExtension widgets configured
 * Providing buttons to open WebChat, WebChat with BotService parameters, ChannelSelector and TestExtension
 * Providing auto-fill of Chat Registration Form (using before() method)
 * Providing support for Chat v2 (polling, cometd long-polling, websocket)
 *
 ************************************************************************/

var localWidgetPlugin;
var callbackInfo = "";
var fldNote = "";
var interactionOverride = "";
var serviceType = "";
var serviceSubType = "";
var verintRecordingFlag = "_";
var wrapUpTime = "999";
const USER_MESSAGE_TO_SHOW_SURVEY = 3;
const AGENT_MESSAGE_TO_SHOW_SURVEY = 3;
const WEBCHAT_COOKIE_NAME = '_genesys.widgets.webchat.state.pureengage-v3-rest.session';
const SESSION_ID_COOKIE_NAME = '_genesys.widgets.webchat.state.session.id';
const SESSION_ID_COOKIE_PATH = 'path=/';
const SESSION_ID_COOKIE_DOMAIN_PATH = 'domain=vodafone.com.au';
const SESSION_ID_COOKIE_DAYS_TO_EXPIRE = 2;
const SURVEY_TITLE = "How did we do?";
const REACTIVE_SURVEY_URL_PREFIX = "https://survey.vodafone.com.au/collection/collection.aspx?cguid=028-e8a59fe0c06b&langid=1&sessionCustomText1=";
const PROACTIVE_SURVEY_URL_PREFIX = "https://survey.vodafone.com.au/collection/collection.aspx?cguid=d94-ebed995c6a0b&langid=1&sessionCustomText1=";

// ##### Document Define Local Customization

// ##### Widget Define Local Customization

var queueArray = {
    "VF_CARE_VQ"            : "VQ_SK_ConsumerCare_CB",
    "VF_BUSINESS_CARE_VQ"   : "VQ_SK_BusinessCare_CB",
    "VF_COLLECTIONS_VQ"     : "VQ_SK_PaymentArrangement_CB",
    "VF_DIRECT_SALES_VQ"    : "VQ_SK_DirectSales_CB",
    "VF_MNP_VQ"             : "VQ_SK_MNP_CB",
    "VF_NBN_CARE_VQ"        : "VQ_SK_NBNCare_CB",
    "VF_NBN_SALES_VQ"       : "VQ_SK_NBNSales_CB",
    "VF_NBN_TECH_SUPPORT_VQ": "VQ_SK_NBNTechSupportL1_CB",
    "VF_PREPAID_CARE_VQ"    : "VQ_SK_PrepaidCare_CB",
    "VF_RESOLUTIONS_VQ"     : "VQ_SK_Resolutions_CB",
    "VF_SAVES_VQ"           : "VQ_SK_Saves_CB",
    "VF_TECH_SUPPORT_VQ"    : "VQ_SK_TechSupportL1_CB",
    "VF_UPGRADES_VQ"        : "VQ_SK_Upgrades_CB"
};

var widgetUtils = new WidgetUtils();
var surveyUtils = new SurveyUtils();

window._genesys.widgets.onReady = function (QuickBus) {
    console.log("localWidgetPlugin getting loaded");

    localWidgetPlugin = CXBus.registerPlugin('MyLocalCustomization');
    if (window.localWidgetPluginCallback) {
        window.localWidgetPluginCallback();
    }
    if (localWidgetPlugin) {
        surveyUtils.subscribeSurveyRelatedEvents();
    }
};

var validate_DateTime = function(e, ndWrapper, ndInput, ndLabel, $){

    if(document.getElementById("cx_form_schedule_time")) {

        var ndDateTime = $("#cx_form_schedule_time"),
            ndSelectOption = $("select[name='scheduletime']");

        if (ndDateTime.val()) {

            $("#cx_form_schedule_time").removeClass("cx-error");
            return true;

        } else if(ndSelectOption.hasClass('cx-hide')){

            $("#cx_form_schedule_time").addClass("cx-error");
            return false;
        }
    }

    return true;
};

var validate_PhoneNumber = function(e, ndWrapper, ndInput, ndLabel, $){

    if(document.getElementById("cx_form_callback_phone_number")) {

        var ndPhoneNumber = $("#cx_form_callback_phone_number");

        if (ndPhoneNumber.val().startsWith("0")) {
            document.getElementById("cx_form_callback_phone_number").value = ndPhoneNumber.val().replace('0','61');
        }else if (ndPhoneNumber.val().startsWith("610")) {
            document.getElementById("cx_form_callback_phone_number").value = ndPhoneNumber.val().replace('610','61');
        }else if (ndPhoneNumber.val().length != 11){
            return false;
        }

        if (ndPhoneNumber.val().startsWith("612") || ndPhoneNumber.val().startsWith("613") || ndPhoneNumber.val().startsWith("614")
            || ndPhoneNumber.val().startsWith("617") || ndPhoneNumber.val().startsWith("618")) {

            $("#cx_form_callback_phone_number").removeClass("cx-error");
            return true;

        } else {
            $("#cx_form_callback_phone_number").addClass("cx-error");
            return false;
        }
    }

    return true;
};


window.getKeyByValue = function(object, value) {
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (object[prop] === value)
                return prop;
        }
    }
};

window.initAndOpenCallbackForm = function () {
    var query = window.location.search.substring(1);
    var vars = query.split("&");

    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == 'queue') {
            if(pair[1].indexOf("_CB")!=-1) {
                OpenCallbackForm(pair[1]);
            } else if(pair[1].indexOf("_VQ")!=-1) {
                OpenCallbackForm(queueArray[pair[1]]);
            } else {
                OpenCallbackForm(queueArray[pair[1]+"_VQ"]);
            }
        }
    }
};

window.OpenCallbackForm = function (queuename, agentCallback) {

    console.log("Queue name passed from button click:"+queuename);
    var queueName ;

    if(queuename)
        queueName = queuename;
    else
        queueName = 'VQ_SK_ConsumerCare_CB';
    console.log("queueName:"+queueName);

    if(queuename.includes("MNP"))
        interactionOverride = "";
    else
        interactionOverride = "VF_Inbound_WWE_Override_Mandatory";

    var callbackNotes ;

    if (agentCallback) {
        callbackInfo = "AWCB";
        fldNote = "Agent Web CB";
        callbackNotes = "Agent WCB";
    } else {
        callbackInfo = "CWCB";
        fldNote = "Cust Web CB";
        callbackNotes = "";
    }
    console.log("callbackNotes:"+callbackNotes);

    serviceType = getKeyByValue(queueArray,queueName);
    if(serviceType.endsWith("_VQ"))
        serviceType = serviceType.substring(0,serviceType.length-3);

    fldNote = serviceType +  " - " + fldNote;


    if(queueName.endsWith("_CB"))
        serviceSubType = queueName.substring(0,queueName.length-3);
    if(queueName.startsWith("VQ_"))
        serviceSubType = serviceSubType.substring(3);


    window._genesys.widgets.callback = {
        //dataURL: gmsServicesConfig.GMSChatURL,
        dataURL: 'https://gapi-aus4.genesyscloud.com/engagement/v3/callbacks',
        apiVersion: "v3",
        apikey: "4cf3ad80-83bc-478f-8999-8206fe70fd54",
        callDirection: "USERTERMINATED",
        immediateCallback: true,
        scheduledCallback: true,
        serviceName: queueName,
        ewt: {
            display: true,
            queue: queueName,
            threshold: 2000,
            refreshInterval: 10,
            immediateCallback: {
                thresholdMin: 1000,
                thresholdMax: 3000
            }
        },
        countryCodes: false,
    };

    if(confirm("One of our team members can call you back at a time that's convenient for you. \n\nTo receive a call back you'll need an Australian mobile number or landline with area code. \n\nIf you've requested a call back and you're outside Australia, international call rates may apply.")){
        console.log("callbackInfo:"+callbackInfo);

        if (localWidgetPlugin) {

            CXBus.command("CallbackService.configure", {
                serviceName: queueName,
                ewt: {
                    queue: queueName // new queue name
                }
            }).done(function () {
                CXBus.command("Callback.configure", {
                    ewt: {
                        display: true,
                        queue: queueName // new vqname
                    }
                }).done(function() {

                    localWidgetPlugin.command('Callback.open', {
                            formJSON: {
                                wrapper: "<table></table>",
                                inputs: [

                                    {
                                        id: "cx_form_callback_firstname",
                                        name: "firstname",
                                        maxlength: "50",
                                        placeholder: "@i18n:callback.CallbackPlaceholderOptional",
                                        label: "@i18n:callback.CallbackFirstName"
                                    },

                                    {
                                        id: "cx_form_callback_lastname",
                                        name: "lastname",
                                        maxlength: "50",
                                        placeholder: "@i18n:callback.CallbackPlaceholderOptional",
                                        label: "@i18n:callback.CallbackLastName"
                                    },

                                    {
                                        id: "cx_form_callback_phone_number",
                                        name: "phonenumber",
                                        maxlength: "11",
                                        placeholder: "@i18n:callback.CallbackPlaceholderPhone",
                                        label: "@i18n:callback.CallbackPhoneNumber",
                                        onkeypress: function(event) {
                                            // To allow only number inputs
                                            return (event.charCode >= 48 && event.charCode <= 57)
                                        },
                                        validateWhileTyping: true,
                                        validate: validate_PhoneNumber
                                    },

                                    {
                                        id: "cx_form_callback_subject",
                                        name: "subject",
                                        type: "textarea",
                                        maxlength: "100",
                                        placeholder: "@i18n:callback.CallbackPlaceholderNotes",
                                        label: "@i18n:callback.CallbackNotes"
                                    },

                                    {
                                        id: "cx_form_schedule_time_hidden", // hidden form field.
                                        name: "desiredtime_hidden",
                                        type: "hidden",
                                        validate: validate_DateTime
                                    }
                                ]
                            },
                            form: {
                                subject: callbackNotes
                            },
                            userData: {
                                org:'Vodafone Australia',
                                FLD_NOTE: fldNote,
                                VERINT_RECORDING_FLAG: verintRecordingFlag,
                                WrapUpTime: wrapUpTime,
                                ServiceType: serviceType,
                                ServiceSubType: serviceSubType,
                                Interaction_Override: interactionOverride,
                                serviceName: queueName,
                                CALLBACK_ORIGIN: callbackInfo
                            }
                        }
                    ).done(function (e) {
                        // WebChat opened successfully
                    }).fail(function (e) {
                    });

                });

            });

        }
    }

};

// ##### WebChat

var consumerInputs = [
    {
        id: "cx_webchat_form_firstname",
        name: "firstname",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderFirstName",
        label: "@i18n:webchat.ChatFormFirstName",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(input && input[0].value);
        }
    },
    {
        id: "cx_webchat_form_lastname",
        name: "lastname",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderLastName",
        label: "@i18n:webchat.ChatFormLastName",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(input && input[0].value);
        }
    },
    {
        id: "cx_webchat_form_phonenumber",
        name: "PhoneNumber",
        maxlength: "11",
        placeholder: "@i18n:webchat.ChatFormPlaceholderPhoneNumber",
        label: "@i18n:webchat.ChatFormPhoneNumber",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(input && input[0].value && /\d{10,11}/.test(input[0].value));
        }
    },
    {
        id: "cx_webchat_form_pin",
        name: "PIN",
        type: "password",
        maxlength: "4",
        placeholder: "@i18n:webchat.ChatFormPlaceholderPin",
        label: "@i18n:webchat.ChatFormPin",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return !input || !input[0].value || /^\d{4}$/.test(input[0].value);
        }
    },
    {
        id: "cx_webchat_form_email",
        name: "EmailAddress",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderEmail",
        label: "@i18n:webchat.ChatFormEmail",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(input && input[0].value && /.+@.+\..+/.test(input[0].value));
        }
    }
];

var b2bInputs = [
    {
        id: "cx_webchat_form_firstname",
        type: "hidden",
        name: "firstname",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderFirstName",
        label: "@i18n:webchat.ChatFormFirstName"
    },
    {
        id: "cx_webchat_form_name",
        name: "name",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderName",
        label: "@i18n:webchat.ChatFormName",
        validate: function (event, form, input, label, $, CXBus, Common) {
            if (input) {
                document.getElementById("cx_webchat_form_firstname").value = input[0].value;
            }
            return Boolean(input && input[0].value && /^[a-z][a-z\-\s]*$/i.test(input[0].value));
        }
    },
    {
        id: "cx_webchat_form_rowid",
        name: "Row_ID_Number",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderRowId",
        label: "@i18n:webchat.ChatFormRowId",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(!input || !input[0].value || /^[a-z0-9\-]+$/i.test(input[0].value));
        }
    },
    {
        id: "cx_webchat_form_pin",
        name: "PIN",
        type: "password",
        maxlength: "4",
        placeholder: "@i18n:webchat.ChatFormPlaceholderPin",
        label: "@i18n:webchat.ChatFormPin",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return !input || !input[0].value || /^\d{4}$/.test(input[0].value);
        }
    },
    {
        id: "cx_webchat_form_employeeid",
        name: "Store_Code",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderEmployeeId",
        label: "@i18n:webchat.ChatFormEmployeeId",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(input && input[0].value && /^[a-z0-9]+$/i.test(input[0].value));
        }
    },
    {
        id: "cx_webchat_form_password",
        name: "Weekly_Password",
        type: "password",
        maxlength: "100",
        placeholder: "@i18n:webchat.ChatFormPlaceholderPassword",
        label: "@i18n:webchat.ChatFormPassword",
        validate: function (event, form, input, label, $, CXBus, Common) {
            return Boolean(input && input[0].value && /^[a-z0-9]+$/i.test(input[0].value));
        }
    }
];

function SurveyUtils() {
    const that = this;
    const cookieUtils = new CookieUtils();

    SurveyUtils.prototype.setSurveyTitle = function () {
        $('.cx-title').text(SURVEY_TITLE);
    };

    SurveyUtils.prototype.showSurvey = function (sessionId, isProactive) {
        const surveyUrlPrefix = (isProactive === false) ? REACTIVE_SURVEY_URL_PREFIX : PROACTIVE_SURVEY_URL_PREFIX;
        const surveyEndPoint = surveyUrlPrefix + sessionId;

        const overlayCommandOptions = {
            html: "<iframe src='" + surveyEndPoint + "' style='height: inherit;'></iframe>",
            hideFooter: true
        };
        widgetUtils.executeWidgetCommand('WebChat.showOverlay', overlayCommandOptions, that.setSurveyTitle);
    };

    SurveyUtils.prototype.prepareToShowSurvey = function (event) {
        const data = event.data;
        const sessionId = cookieUtils.getCookieValue(SESSION_ID_COOKIE_NAME);
        if (sessionId) {
            if (typeof data !== 'undefined'
                && data
                && data.userMessages > USER_MESSAGE_TO_SHOW_SURVEY
                && data.agentMessages > AGENT_MESSAGE_TO_SHOW_SURVEY
            ) {
                that.showSurvey(sessionId, data.proactiveData);
            }
            that.deleteCookie();
        }
    };

    SurveyUtils.prototype.deleteCookie = function () {
        cookieUtils.deleteCookie(SESSION_ID_COOKIE_NAME, SESSION_ID_COOKIE_PATH, SESSION_ID_COOKIE_DOMAIN_PATH);
    };

    SurveyUtils.prototype.storeSessionId = function () {
        const sessionId = cookieUtils.getCookieValue(WEBCHAT_COOKIE_NAME);
        if (sessionId) {
            cookieUtils.createCookie(SESSION_ID_COOKIE_NAME, sessionId, SESSION_ID_COOKIE_PATH, SESSION_ID_COOKIE_DOMAIN_PATH, SESSION_ID_COOKIE_DAYS_TO_EXPIRE)
        }
    };

    SurveyUtils.prototype.subscribeSurveyRelatedEvents = function () {
        widgetUtils.subscribeWebChatEvent('WebChat.cancelled', surveyUtils.deleteCookie);
        widgetUtils.subscribeWebChatEvent('WebChat.completed', surveyUtils.prepareToShowSurvey);
        widgetUtils.subscribeWebChatEvent('WebChatService.started', surveyUtils.storeSessionId);
    }
}

function CookieUtils() {
    CookieUtils.prototype.getCookieValue = function (name) {
        const cookies = "; " + document.cookie;
        const parts = cookies.split("; " + name + "=");
        return (parts.length === 2) ? decodeURIComponent(parts.pop().split(";").shift()) : '';
    };

    CookieUtils.prototype.createCookie = function (cookieName, cookieValue, path, domainPath, daysToExpire) {
        let date = new Date();
        date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
        document.cookie = encodeURIComponent(cookieName) + "=" + encodeURIComponent(cookieValue) + "; expires=" + date.toGMTString() + "; " + path + "; " + domainPath;
    };

    CookieUtils.prototype.deleteCookie = function (cookieName, path, domainPath) {
        document.cookie = encodeURIComponent(cookieName) + "= ; expires = Thu, 01 Jan 1970 00:00:00 GMT; " + path + "; " + domainPath;
    };
}

function WidgetUtils() {
    WidgetUtils.prototype.executeWidgetCommand = function (command, commandOptions, doneCallback) {
        localWidgetPlugin.command(
            command, commandOptions
        ).done(function (e) {
            if (doneCallback) {
                doneCallback();
            }
        }).fail(function (e) {
            // WebChat isn't open
        });
    };

    WidgetUtils.prototype.subscribeWebChatEvent = function (eventName, callback) {
        localWidgetPlugin.subscribe(eventName, function (e) {
            callback(e);
        });
    }
}

window.OpenWebChatForm = function (queuename, inputs) {
    if (localWidgetPlugin) {
        const openCommandOptions = {
            formJSON: {
                inputs: inputs
            },
            userData: {
                category: queuename
            }
        };
        widgetUtils.executeWidgetCommand('WebChat.open', openCommandOptions);
    }
};