
// VOIP Awesome Click-and-Dial Extension for Google Chrome
// Settings Script
//
//  Copyright:  VOIP Awesome Inc, 2021
//  Author:     Jambu Atchison
//  @ Support:  cs@voipawesome.com
//


// Variables
if (typeof CND == 'undefined') { var CND = {}; }
if (typeof CND.settings == 'undefined') { CND.settings = {}; }
CND.online = window.navigator.onLine;
CND.settings.verify = { pin : '', key : '' };
CND.settings.msgs = {
    failedAuthentication : "We failed to authenticate your account. Please check your credentials and try again."
};
CND.settings.tpl = {
    get_pin_btn_html : '<span class="far fa-phone" aria-hidden="true"></span> Call Me with my PIN',
    new_pin_btn_html : '<span class="far fa-sync" aria-hidden="true"></span> Get a New PIN',
    domain_span : function() {
        if (typeof CND.defaultSettings.domain == 'undefined') { CND.getDefaultInfo(); }
        let domain = CND.getValue('string', false, CND.accountSettings.domain, CND.defaultSettings.domain);
        return '<span class="far fa-globe" aria-hidden="true"></span> Domain: ' + domain;
    },
    extension_span : function() {
        if (typeof CND.defaultSettings.extension == 'undefined') { CND.getDefaultInfo(); }
        let extension = CND.getValue('string', false, CND.accountSettings.extension, CND.defaultSettings.extension);
        return '<span class="far fa-phone-office" aria-hidden="true"></span> Extension: ' + extension;
    }
};


// Functions
if (typeof CND.handleIsLoaded == 'undefined') {
    CND.handleIsLoadedWait = 1;
    CND.handleIsLoadedTimeout = null;
    CND.handleIsLoaded = function(fn='', successCallback=null, failureCallback=null, maxWait=10000, type='function') {
        if (!((typeof fn == 'string') && (fn !== ''))) { return; }
        if (CND.handleIsLoadedTimeout !== null) { clearTimeout(CND.handleIsLoadedTimeout); }
        CND.handleIsLoadedTimeout = setTimeout(function() {
            if (typeof fn == type) {
                if (typeof successCallback == 'function') { setTimeout(function() { successCallback(); }, 1); }
            } else if ((typeof fn == 'string') && (typeof CND != 'undefined') && (typeof CND[fn] == type)) {
                if (typeof successCallback == 'function') { setTimeout(function() { successCallback(); }, 1); }
            } else if (CND.popup.handleIsLoadedWait < maxWait) {
                CND.handleIsLoadedWait = CND.handleIsLoadedWait + CND.handleIsLoadedWait * 3;
                CND.handleIsLoaded(fn, successCallback, failureCallback, maxWait);
            } else {
                if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
            } // end if fn
        }, CND.handleIsLoadedWait);
    }; // end function CND.handleIsLoaded
} // end if handleIsLoaded

CND.settings.handleOnReady = function() {
    CND.settings.handleInit();
    document.addEventListener("beforeunload", function() { CND.saveCurrentWindowPosition(); });
    document.addEventListener("blur", function() { CND.saveCurrentWindowPosition(); });
    document.addEventListener("mousein", function() { CND.saveCurrentWindowPosition(); });
    document.addEventListener("mouseout", function() { CND.saveCurrentWindowPosition(); });
    document.addEventListener("focus", function() { CND.saveCurrentWindowPosition(); });
    document.addEventListener("unload", function() { CND.saveCurrentWindowPosition(); });
    document.addEventListener("resize", function() { CND.saveCurrentWindowPosition(); });
}; // end function CND.settings.handleOnReady

CND.settings.handleInit = function() {
    CND.setFooterVersion();
    try {
        CND.dom(document).bind('contextmenu', function() {
            return false;
        }); // end bind contextmenu
    } catch (e) { console.log(e); return false; }

    //if (!CND.isInstalled) { console.log('Loaded unpacked'); }
    try {
        CND.dom('#btn_cancel_edits').off('click').on('click', function() {
            CND.settings.handleCancelEdits();
        }); // end click btn_cancel_edits
        CND.dom('#btn_get_pin').off('click').on('click', function() {
            CND.settings.handleSubmitGetPIN();
        }); // end click btn_get_pin
        CND.dom('#btn_get_key').off('click').on('click', function() {
            CND.settings.handleSubmitGetApiKey();
        }); // end click btn_get_key
        CND.dom('#btn_edit_settings').off('click').on('click', function() {
            CND.settings.editAccount();
        });
        CND.dom('[data-toggle=confirmation]').confirmation({
            placement : 'bottom',
            onConfirm : function() {
                CND.settings.removeAccount();
            }
        }); // end confirmation
    } catch (e) { console.log(e); return false; }

    CND.ui.handleFormEnter('#add_extension_info', function() {
        CND.settings.handleSubmitGetPIN();
    });

    CND.settings.getAccountInfo();
}; // end function CND.settings.handleInit

CND.settings.handleShowError = function(error_msg='', callbackFunction=null) {
    if (error_msg != '') { CND.ui.showError(error_msg); } else { CND.ui.hideError(); }
    CND.ui.hide('#settings-loading-section');
    CND.ui.hide('#settings-offline-section');
    CND.ui.show('#settings-menu-section');
    CND.ui.show('#settings-menu-list');
    CND.ui.show('#settings-menu-page-info');
    CND.ui.show('#settings-main-section');
    if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
}; // end function CND.settings.handleShowError

CND.settings.handleShowOffline = function(callbackFunction=null) {
    CND.ui.hideError();
    CND.ui.hide('#settings-main-section');
    CND.ui.hide('#settings-loading-section');
    CND.ui.hide('#settings-menu-section');
    CND.ui.hide('#settings-menu-list');
    CND.ui.hide('#settings-menu-page-info');
    CND.ui.show('#settings-offline-section');
    if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
}; // end function CND.settings.handleShowOffline

CND.settings.handleShowMainLoading = function(callbackFunction=null) {
    CND.ui.hideError();
    CND.ui.hide('#settings-offline-section');
    CND.ui.hide('#settings-main-section');
    CND.ui.hide('#settings-menu-section');
    CND.ui.hide('#settings-menu-list');
    CND.ui.hide('#settings-menu-page-info');
    CND.ui.show('#settings-loading-section');
    if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
}; // end function CND.settings.handleShowMainLoading

CND.settings.handleShowMain = function(callbackFunction=null) {
    CND.ui.hideError();
    CND.ui.hide('#settings-offline-section');
    CND.ui.hide('#settings-loading-section');
    CND.ui.show('#settings-menu-section');
    CND.ui.show('#settings-menu-list');
    CND.ui.show('#settings-menu-page-info');
    CND.ui.show('#settings-main-section');
    if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
}; // end function CND.settings.handleShowMain

CND.settings.showRegisteredExtInfo = function(callbackFunction=null) {
    CND.ui.html('#registered_domain', CND.settings.tpl.domain_span);
    CND.ui.html('#registered_extension', CND.settings.tpl.extension_span);
    CND.ui.hide('#add_extension_info');
    CND.ui.hide('#form-group-pin');
    try {
        CND.ui.hide(CND.dom('#btn_cancel_edits').parent());
        CND.ui.hide(CND.dom('#btn_get_pin').parent());
        CND.ui.hide(CND.dom('#btn_get_key').parent());
    } catch (e) { console.log(e); }
    CND.loadExtensionPage('settings.html');
    //CND.settings.handleShowMain();
    //CND.ui.show('#registered_extension_info');
    //if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
}; // end function CND.settings.showRegisteredExtInfo

CND.settings.showAddExtInfoForm = function(callbackFunction=null) {
    CND.ui.hide('#registered_extension_info');
    try {
        CND.dom('#btn_get_pin').html(CND.settings.tpl.get_pin_btn_html);
        CND.ui.hide('#form-group-pin');
        CND.ui.hide(CND.dom('#btn_get_key').parent());
        CND.ui.show(CND.dom('#btn_get_pin').parent());
        let valid = CND.accountSettings.valid ?? false;
        if (valid) {
            CND.ui.show(CND.dom('#btn_cancel_edits').parent());
        }
    } catch (e) { console.log(e); }
    CND.settings.handleShowMain();
    CND.ui.showError(CND.signup_message);
    CND.ui.show('#add_extension_info');
    if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
}; // end function CND.settings.showAddExtInfoForm

CND.settings.getAccountInfo = function(successCallback, failureCallback) {
    console.log('CND.settings.getAccountInfo exec');
    CND.getAccountInfo(function() {
        console.log('CND.getAccountInfo success');
        CND.checkApiKey(function() {
            console.log('CND.checkApiKey success');
            CND.settings.showRegisteredExtInfo();
            if (typeof successCallback == 'function') { setTimeout(function() { successCallback(); }, 1); }
        }, function(xhr, error, message) {
            console.log('CND.checkApiKey failure', xhr);
            if (typeof xhr.status != 'undefined') {
                if (xhr.status == 403) { CND.settings.removeAccount(); }
            }
            CND.settings.showAddExtInfoForm();
            if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
        }, function() {
            console.log('CND.checkApiKey offline');
            CND.settings.handleShowOffline();
        });
    }, function() {
        console.log('CND.getAccountInfo failure');
        CND.settings.showAddExtInfoForm();
        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
    }, false);
}; // end function CND.settings.getAccountInfo

CND.settings.handleCancelEdits = function() {
    CND.ui.hide('#add_extension_info');
    CND.settings.handleShowMain();
    CND.ui.show('#registered_extension_info');
}; // end function CND.settings.handleCancelEdits

CND.settings.handleSubmitGetPIN = function() {
    let domain = CND.dom('#domain').val();
    let extension = CND.dom('#extension').val();
    //if (!CND.isInstalled) { console.log('Loaded unpacked'); }
    CND.settings.getExtensionPIN(domain, extension, function(domain, extension, verify_pin) {
        CND.settings.verify.pin = verify_pin;
        CND.setAccountInfo(domain, '', extension, false);
        CND.ui.handleFormEnter('#add_extension_info', function() {
            CND.settings.handleSubmitGetApiKey();
        });
    }, function() {
        CND.ui.showError(CND.settings.msgs.failedAuthentication);
    });
}; // end function CND.settings.handleSubmitGetPIN

CND.settings.getExtensionPIN = function(domain, extension, successCallback, failureCallback) {
    let requestApiUrl = CND.getApiUrl(domain, true);
    let data = {
        'action': 'get_pin',
        'domain': domain,
        'ext': extension
    };
    let dataParams = CND.serializeParams(data);
    CND.dom('#pin').val('');
    CND.settings.verify.pin = '';
    CND.ajax({
        type: 'POST',
        dataType: 'json',
        url: requestApiUrl,
        data: dataParams,
        error:function() {
            CND.ui.showError('Connection to Authentication Server Failed');
        },
        success: function(data) {
            if ((typeof data.status != 'undefined') && (data.status == 1)) {
                let verify_pin = data.verify ?? '';
                CND.settings.verify.pin = verify_pin;
                CND.pbxApiUrl = CND.getApiUrl(domain, true);
                try {
                    CND.dom('#btn_get_pin').html(CND.settings.tpl.new_pin_btn_html);
                    CND.ui.show('#form-group-pin');
                    CND.ui.show(CND.dom('#btn_get_pin').parent());
                    CND.ui.show(CND.dom('#btn_get_key').parent());
                    let valid = CND.accountSettings.valid ?? false;
                    if (valid) {
                        CND.ui.show(CND.dom('#btn_cancel_edits').parent());
                    }
                } catch (e) { console.log(e); }
                CND.ui.hideError();
                CND.ui.showSuccess('Please answer the call ringing on your desktop or softphone device, and enter the PIN provided.');
                if (typeof successCallback == 'function') { setTimeout(function() { successCallback(domain, extension, verify_pin); }, 1); }
            } else {
                try {
                    CND.dom('#btn_get_pin').html(CND.settings.tpl.get_pin_btn_html);
                    CND.ui.hide('#form-group-pin');
                    CND.ui.show(CND.dom('#btn_get_pin').parent());
                    CND.ui.hide(CND.dom('#btn_get_key').parent());
                    let valid = CND.accountSettings.valid ?? false;
                    if (valid) {
                        CND.ui.show(CND.dom('#btn_cancel_edits').parent());
                    }

                } catch (e) { console.log(e); }
                if (typeof data.error != 'undefined') {
                    CND.ui.showError('The account credentials provided are not valid, please try again.');
                } else {
                    CND.ui.showError('An Unexpected Error Occurred. Error #209');
                } // end if data.error
                if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
            } // end if data.success
        } // end Success
    }); // end ajax
}; // end function CND.settings.getExtensionPIN

CND.settings.handleSubmitGetApiKey = function() {
    let domain = CND.dom('#domain').val();
    let extension = CND.dom('#extension').val();
    let pin = CND.dom('#pin').val();
    //if (!CND.isInstalled) { console.log('Loaded unpacked'); }
    CND.settings.verify.key = '';
    CND.settings.getExtensionApiKey(domain, extension, pin, function(domain, extension, key) {
        //console.log('CND.settings.getExtensionApiKey success');
        CND.settings.verify.key = key;
        CND.setAccountInfo(domain, key, extension, false);
        CND.settings.getAccountInfo();
        setTimeout(function() {
            try {
                if (CND.dom('#settings-menu-chats-link').length > 0) {
                    CND.loadExtensionPage('chat.html');
                } // end if settings page
            } catch (e) { console.log(e); }
        }, 3000);
    }, function() {
        //console.log('CND.settings.getExtensionApiKey failure');
        CND.ui.showError(CND.settings.msgs.failedAuthentication);
    });
}; // end function CND.settings.handleSubmitGetApiKey

CND.settings.getExtensionApiKey = function(domain, extension, pin, successCallback, failureCallback) {
    let requestApiUrl = CND.getApiUrl(domain, true);
    let data = {
        'action': 'get_key',
        'domain': domain,
        'ext': extension,
        'verify': CND.settings.verify.pin,
        'pin': pin
    };
    try {
        let dataParams = CND.serializeParams(data);
        CND.ajax({
            type: 'POST',
            dataType: 'json',
            url: requestApiUrl,
            data: dataParams,
            error: function() {
                CND.ui.showError('Connection to Authentication Server Failed');
                if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
            },
            success: function(data) {
                if ((typeof data.status != 'undefined') && (data.status == 1)) {
                    let key = data.key ?? '';
                    CND.settings.verify.key = key;
                    CND.pbxApiUrl = CND.getApiUrl(domain, false);
                    try {
                        CND.ui.hide(CND.dom('#btn_get_pin').parent());
                        CND.ui.hide(CND.dom('#btn_get_key').parent());
                        CND.ui.hide(CND.dom('#btn_cancel_edits').parent());
                        CND.ui.hideError();
                        CND.ui.showSuccess('The account credentials have been validated, you may now use the VOIP Awesome Chat & Dial extension');
                        if (typeof successCallback == 'function') { setTimeout(function() { successCallback(domain, extension, key); }, 1); }
                    } catch (e) {
                        console.log(e);
                        CND.ui.showError('An Unexpected Error Occurred. Error #275');
                        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                    } // end try jquery
                } else if (typeof data.error != 'undefined') {
                    CND.ui.showError('The account credentials provided are not valid, please try again.');
                    if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                } else {
                    CND.ui.showError('An Unexpected Error Occurred. Error #282');
                    if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                } // end if data.success || data.error
            } // end Success
        }); // end ajax
    } catch (e) {
        console.log(e);
        CND.ui.showError('An Unexpected Error Occurred. Error #289');
        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
    } // end try jquery
}; // end function CND.settings.getExtensionApiKey

CND.settings.removeAccount = function() {
    CND.getDefaultInfo();
    let domain = CND.getValue('string', false, CND.accountSettings.domain, CND.defaultSettings.domain);
    let extension = CND.getValue('string', false, CND.accountSettings.extension, CND.defaultSettings.extension);
    try {
        CND.dom('#domain').val(domain);
        CND.dom('#extension').val(extension);
        CND.dom('#pin').val('');
        CND.dom('#btn_get_pin').html(CND.settings.tpl.get_pin_btn_html);
        CND.ui.hide(CND.dom('#btn_get_key').parent());
        CND.ui.show(CND.dom('#btn_get_pin').parent());
        let valid = CND.accountSettings.valid ?? false;
        if (valid) {
            CND.ui.show(CND.dom('#btn_cancel_edits').parent());
        }
    } catch (e) { console.log(e); }
    if (!CND.isInstalled) { console.log('Installed Unpacked'); }
    CND.settings.verify.pin = '';
    CND.ui.hide('#form-group-pin');
    CND.ui.hide('#registered_extension_info');
    CND.settings.handleShowMain();
    CND.ui.show('#add_extension_info');
    CND.setAccountInfo('', '', '', false);
}; // end function CND.settings.removeAccount

CND.settings.editAccount = function() {
    CND.getDefaultInfo();
    let domain = CND.getValue('string', false, CND.accountSettings.domain, CND.defaultSettings.domain);
    let extension = CND.getValue('string', false, CND.accountSettings.extension, CND.defaultSettings.extension);
    CND.ui.hide('#form-group-pin');
    CND.ui.hide('#registered_extension_info');
    CND.settings.verify.pin = '';
    try {
        CND.dom('#domain').val(domain);
        CND.dom('#extension').val(extension);
        CND.dom('#pin').val('');
        CND.dom('#btn_get_pin').html(CND.settings.tpl.get_pin_btn_html);
        CND.ui.hide(CND.dom('#btn_get_key').parent());
        CND.ui.show(CND.dom('#btn_get_pin').parent());
        let valid = CND.accountSettings.valid ?? false;
        if (valid) {
            CND.ui.show(CND.dom('#btn_cancel_edits').parent());
        }
    } catch (e) { console.log(e); }
    CND.settings.handleShowMain();
    CND.ui.show('#add_extension_info');
    if (!CND.isInstalled) { console.log('Installed Unpacked'); }
}; // end function CND.settings.editAccount




// Document Ready
document.addEventListener("DOMContentLoaded", function() {
    window.addEventListener('offline', function(e) {
        console.log('offline now');
        if (CND.online) {
            CND.settings.handleShowOffline()
        }
        CND.online = false;
    }); // end offline
    window.addEventListener('online', function(e) {
        console.log('online now');
        if (!CND.online) { setTimeout(function() { location.reload(); }, 1); }
        CND.online = true;
    }); // end online


    CND.handleIsLoaded('getAccountInfo', function() {
        CND.settings.handleOnReady();
    });
}); // end document ready

