/**
 *  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
 * 
 * 
 * Defines the functionality for the logon window
 */

var chatLogon = {

    /**
    * The attributes for the chat. There is a known issue where Work Assignment does not accept any contact
    * whose contextId has more than 10 attributes associated with it. Those attributes include this array *AND*
    */
    attributes : [ 'Location.Inhouse' ],

    // Work Assignment requires not more than 10 attributes (channel + 9 attributes) per service.
    attributeCount : 1,
    maxAttributes : 9,


    /**
     * Logs the customer into the chat.
     * @param {JSON} custDetails - JSON object that wraps up the customer details
     */
    logon : function(custDetails) {
        'use strict';
        chatUI.changeToChatMode();
        webChat.initChat(true, custDetails);
    },
    
    /**
     * Check the email validity while the customer is typing. Called from the email type input itself, using an oninput event.
     * @param {HTMLElement} el - the email input that calls this method.
     */
    checkEmailValidity: function(el) {
        'use strict';
        var isEmailValid = el.checkValidity() && el.value.trim().length > 0;
        chatUI.setEmailInputValid(isEmailValid);
    },
	
    /**
     * Validate phone details
     * @param {Object} country
     * @param {Object} area
     * @param {Object} phone
     * @returns {Boolean} - true if the details are valid
     */
    validatePhone : function(country, area, phone) {
        'use strict';

        // Allow blank if no phone number required
        if (country.value + area.value + phone.value === '' && !chatConfig.requirePhone){
            return true;
        } else {
            // Check if the phone number is valid
            // Country codes are optional to facilitate lab testing with internal numbers
            // Some countries (e.g. Singapore) do not use area codes, so these are optional as well
            var reCountry = new RegExp("^("+country.pattern+"|)$");
            var reArea = new RegExp("^("+area.pattern + "|)$");
            var rePhone = new RegExp("^"+phone.pattern+"$");
            
            return (reCountry.test(country.value) && reArea.test(area.value) && rePhone.test(phone.value));
        }
    },

    /**
     * Gathers the customer's details before logging them in.
     */
    gatherDetails : function() {
        'use strict';
        var isStringEmpty = avayaGlobal.isStringEmpty;
        var details = chatUI.getCustomerDetails();
        var l_user = details.firstName, l_user_last = details.lastName, l_email = details.email;
        var phoneDetails = chatUI.getPhoneDetails();
	
        // gather custom fields
        var customFields = chatUI.getCustomFields();
        var customFieldTitle = customFields.title;
        var customFieldValue = customFields.value;

        var errors = '';
        
        if (chatConfig.requireEmail && isStringEmpty(l_email)) {
            errors += "A valid email address is required\n";    
        }

        // validate the phone detaiols here
        if (!chatLogon.validatePhone(phoneDetails.country, phoneDetails.area, phoneDetails.phone)) {
            errors += 'A valid phone number is required\n';
        }

        // check if the name is too long
        if (l_user.length > 50) {
            errors += 'Your name is too long. It must be less than 50 characters\n';
        }
        else if (chatConfig.requireFirstName && isStringEmpty(l_user)) {
            errors += "You must provide a first name and last name\n";
        }
        
        if (l_user_last.length > 100) {
            errors += 'Your surname is too long. It must be less than 100 characters\n';
        }
        else if (chatConfig.requireLastName && isStringEmpty(l_user_last)) {
            errors += "You must provide a first name and last name\n";
        }
        
        if (customFieldTitle.length > 50) {
            errors += "Custom Fields titles must be less than 50 characters\n";
        }
        if (customFieldValue.length > 255) {
            errors += "Custom Fields values must be less than 255 characters\n";
        }
        if (isStringEmpty(customFieldTitle) && ! isStringEmpty(customFieldValue)) {
            errors += "A custom field cannot have an empty title\n";
        }
        
        var isTopicValid = chatUI.isTopicValid();
        if (!isTopicValid) {
            errors += "The topic field is invalid\n";
        }
        
        if (errors === '') {
            
            // do not add empty custom fields
            if (!isStringEmpty(customFieldTitle)) {
                webChat.addCustomFields(customFieldTitle, customFieldValue);    
            }
            
            var custDetails = {
                "firstName" : l_user,
                "lastName" : l_user_last,
                "email" : l_email,
                "phone" : {
                    "country" : phoneDetails.country.value,
                    "area" : phoneDetails.area.value,
                    "number" : phoneDetails.phone.value
                }
            };
            
            // save these details for if we need to reload the page
            avayaGlobal.setSessionStorage("custDetails", JSON.stringify(custDetails));
            chatLogon.logon(custDetails);
        } else {
            var message = "Please correct the following errors:\n" + errors;
            chatUI.showLoginErrors(message);
        }

    },

    /**
     * Add an attribute to the chat logon attributes. This does <em>not</em> affect Context Store.
     * @param newAttribute is a String that represents the attribute.
     */
    addAttribute : function(newAttribute) {
        'use strict';
        if (chatLogon.attributes.indexOf(newAttribute) < 0 && chatLogon.attributeCount < chatLogon.maxAttributes) {
            chatLogon.attributes.push(newAttribute);
            chatLogon.attributeCount++;
            chatLogon.saveAttributeCount();
        }
    },

    /**
     * Removes the specified attribute from the chat attributes. This does <em>not</em> affect Context Store.
     * @param oldAttribute is a String that represents the attribute to remove.
     */
    removeAttribute : function(oldAttribute) {
        'use strict';
        var index = chatLogon.attributes.indexOf(oldAttribute);
        chatLogon.attributes.splice(index, 1);
        if (chatLogon.attributeCount > 0) {
            chatLogon.attributeCount--;
            chatLogon.saveAttributeCount();
        }
    },

    /**
     * Save the total attribute count. Part of a workaround for OCPROVIDER-1206
     */
    saveAttributeCount : function() {
        'use strict';
        avayaGlobal.setSessionStorage('chatAttrCount', chatLogon.attributeCount);
    },

    loadAttributeCount : function() {
        'use strict';
        var attr = avayaGlobal.getSessionStorage('totalAttributes');
        chatLogon.attributeCount = attr !== null ? parseInt(attr) : 0;
    }
};
