
// 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.newmsg == 'undefined') { CND.newmsg = {}; }
CND.online = window.navigator.onLine;
CND.newmsg.hash = '';
CND.newmsg.recipients = '';
CND.newmsg.verify = { pin : '', key : '' };
CND.newmsg.msgs = {
    failedAuthentication : "We failed to authenticate your account. Please check your credentials and try again."
};

// 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.newmsg.checkHashRecipients = function(callbackFunction=null) {
    var exec = false;
    if (window.location.hash) {
        CND.newmsg.hash = window.location.hash.substring(1);
        if (CND.newmsg.hash != '') {
            CND.newmsg.recipients = CND.newmsg.hash.split('=')[1];
            if (CND.newmsg.recipients) {
                CND.newmsg.recipients = CND.str.phoneNumber(CND.newmsg.recipients, 'dial')
                console.log('recipients', CND.newmsg.recipients);
                if (CND.newmsg.recipients != '') {
                    try {
                       CND.dom('#new_message_form').find('input[name="recipients"]').val(CND.newmsg.recipients);
                    } catch (e) { console.log(e); }
                    exec = true;
                    setTimeout(function() { CND.newmsg.checkRecipient(CND.newmsg.recipients, callbackFunction); }, 10);
                } // end if CND.newmsg.recipients
            } // end if recipients
        } // end if CND.newmsg.hash
    } // end if hash
    if (!exec) {
        if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 10); }
    }
}; // end function CND.newmsg.checkHashRecipients

CND.newmsg.saveChatsLocal = function(a=0, s=null) {
    // Set information from the Cookies. Nom Nom
    chrome.storage.local.set({ 'chats_active_id' : a, 'chats_search' : s }, function() {
        CND.newmsg.lastActive = a;
        CND.newmsg.lastSearch = s;
    }); // end set storage
}; // end function CND.newmsg.saveChatsLocal

CND.newmsg.handleOnReady = function() {
    CND.newmsg.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(); });
    window.addEventListener("hashchange", function() {
        if (window.location.hash) {
            CND.newmsg.hash = window.location.hash.substring(1);
            if (CND.newmsg.hash != '') {
                setTimeout(function() { CND.reload(); }, 1);
            } // end if CND.newmsg.hash
        } // end if window.location.hash
    }); // end on hashchange
}; // end function CND.newmsg.handleOnReady

CND.newmsg.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.newmsg.handleCancelBtn();
        }); // end click btn_cancel_edits
        CND.dom('#btn_send_msg').off('click').on('click', function() {
            CND.newmsg.handleSendNewMsg();
        }); // end click btn_get_pin
    } catch (e) { console.log(e); return false; }

    CND.ui.handleFormEnter('#new_message_form', function() {
        CND.newmsg.handleSendNewMsg();
    });

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

CND.newmsg.handleCancelBtn = function() {
    CND.newmsg.handleGoToChats();
}; // end function CND.newmsg.handleCancelBtn

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

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

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

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

CND.newmsg.getAccountInfo = function(successCallback, failureCallback) {
    //console.log('CND.newmsg.getAccountInfo exec');
    CND.getAccountInfo(function() {
        //console.log('CND.getAccountInfo success');
        CND.checkApiKey(function() {
            //console.log('CND.checkApiKey success');
            CND.newmsg.checkHashRecipients(function() {
                CND.newmsg.handleShowMain();
                if (typeof successCallback == 'function') { setTimeout(function() { successCallback(); }, 1); }
            });
        }, function() {
            //console.log('CND.checkApiKey failure');
            CND.newmsg.handleShowError(CND.newmsg.msgs.failedAuthentication);
            if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
        }, function() {
            //console.log('CND.checkApiKey offline');
            CND.newmsg.handleShowOffline();
        });
    }, function() {
        //console.log('CND.getAccountInfo failure');
        CND.newmsg.handleShowError(CND.newmsg.msgs.failedAuthentication);
        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
    }, true);
}; // end function CND.newmsg.getAccountInfo

CND.newmsg.handleGoToChats = function() {
    CND.loadExtensionPage('chat.html');
}; // end function CND.newmsg.handleGoToChats

CND.newmsg.handleSendNewMsg = function() {
    CND.newmsg.sendNewMsg(function() {
        setTimeout(function() {
            CND.newmsg.handleGoToChats();
        }, 10);
    }, function() {
        CND.newmsg.handleShowError('Connection to Server Failed');
    });
}; // end function CND.newmsg.handleSendNewMsg

CND.newmsg.checkRecipient = function(destinations='', callbackFunction=null) {
    var domain = CND.accountSettings.domain ?? CND.defaultSettings.domain ?? '';
    var apikey = CND.accountSettings.apikey ?? '';
        destinations = destinations.toString().trim();
    var data = {
        'action': 'check_recipient',
        'domain': domain,
        'key': apikey,
        'destinations' : destinations
    };
    if (destinations == '') {
        if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
        return;
    }
    try {
        var requestApiUrl = CND.getApiUrl(domain, true);
        CND.ajax({
            type: 'POST',
            dataType: 'json',
            url: requestApiUrl,
            data: data,
            error: function(xhr, error, message) {
                //console.log('error', requestApiUrl, xhr, error, message);
                try {
                    if ((typeof xhr != 'undefined') && (xhr !== null)) {
                        if (typeof xhr.status != 'undefined') {
                            if (xhr.status == 403) { CND.loadExtensionPage('settings.html'); }
                        }
                    }
                } catch (e) { console.log(e); }
                if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
            },
            success: function(data) {
                //console.log(data);
                if ((typeof data != 'undefined') && (typeof data.status != 'undefined') && (data.status == 1)) {
                    var chat_group_id = data.chat_group_id ?? 0;
                    if (chat_group_id != 0) {
                        CND.newmsg.saveChatsLocal(chat_group_id, '');
                        setTimeout(function() { CND.newmsg.handleGoToChats(); }, 1);
                        return;
                    } // end if chat_group_id
                } // end if data.success
                if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
            } // end Success
        }); // end ajax
    } catch (e) {
        console.log(e);
        if (typeof callbackFunction == 'function') { setTimeout(function() { callbackFunction(); }, 1); }
    } // end try ajax
}; // end function CND.newmsg.checkRecipient

CND.newmsg.sendNewMsg = function(successCallback, failureCallback) {
    CND.newmsg.handleShowMainLoading();
    var domain = CND.accountSettings.domain ?? CND.defaultSettings.domain ?? '';
    var apikey = CND.accountSettings.apikey ?? '';
    var destinations = '';
    var body = '';
    try {
        CND.dom('#new-msg-destinations').find('.contact-number').each(function(i, e) {
            var destination = CND.dom(e).text();
            destinations.push(destination);
        });
        destinations = CND.dom('#new_message_form').find('input[name="recipients"]').val();
        destinations = destinations.toString().trim();
        body = CND.dom('#new_message_form').find('textarea[name="message"]').val();
        body = body.toString().trim();
    } catch (e) { console.log(e); }
    var data = {
        'action': 'send_msg',
        'domain': domain,
        'key': apikey,
        'group': 0,
        'body': body,
        'destinations' : destinations
    };
    if (destinations == '') {
        CND.newmsg.handleShowError('Message recipient is required');
        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
        return;
    }
    if (body == '') {
        CND.newmsg.handleShowError('Message body is required');
        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
        return;
    }
    try {
        var requestApiUrl = CND.getApiUrl(domain, true);
        CND.ajax({
            type: 'POST',
            dataType: 'json',
            url: requestApiUrl,
            data: data,
            error: function(xhr, error, message) {
                //console.log('error', requestApiUrl, xhr, error, message);
                try {
                    if ((typeof xhr != 'undefined') && (xhr !== null)) {
                        if (typeof xhr.status != 'undefined') {
                            if (xhr.status == 403) { CND.loadExtensionPage('settings.html'); }
                        }
                    }
                } catch (e) { console.log(e); }
                CND.newmsg.handleShowError('Message Failed to Send!', function () {
                    if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                });
            },
            success: function(data) {
                console.log(data);
                if ((typeof data.status != 'undefined') && (data.status == 1)) {
                    try {
                        var chat_group_id = data.chat_group_id ?? 0;
                        CND.newmsg.saveChatsLocal(chat_group_id, '');
                        if (typeof successCallback == 'function') { setTimeout(function() { successCallback(); }, 1); }
                    } catch (e) {
                        console.log(e);
                        CND.newmsg.handleShowError('An Unexpected Error Occurred. Error #326');
                        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                    } // end try jquery
                } else if (typeof data.error != 'undefined') {
                    CND.newmsg.handleShowError('The account credentials provided are not valid, please try again.');
                    if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                } else {
                    CND.newmsg.handleShowError('An Unexpected Error Occurred. Error #333');
                    if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
                } // end if data.success || data.error
            } // end Success
        }); // end ajax
    } catch (e) {
        console.log(e);
        CND.newmsg.handleShowError('An Unexpected Error Occurred. Error #340');
        if (typeof failureCallback == 'function') { setTimeout(function() { failureCallback(); }, 1); }
    } // end try jquery
}; // end function CND.newmsg.sendNewMsg


// Document Ready
document.addEventListener("DOMContentLoaded", function() {
    window.addEventListener('offline', function(e) {
        console.log('offline now');
        if (CND.online) {
            CND.newmsg.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.newmsg.handleOnReady();
    });
}); // end document ready

