try {
    var i = 0;
    var number = '';
    var showAlertFile = false;
    var isPause = false;
    var ExcelVal = [];
    var contactVal = [];
    var Files = [];
    var fileBase = '';
    window.onload = function() {
        if (localStorage.getItem("username") != null) {
            document.getElementById("LoginBox").classList.add('hide');
            document.getElementById("sendMessageBox").classList.remove('hide');
        } else if (localStorage.getItem("email") != null && localStorage.getItem("email") != "") {
            document.getElementById("LoginForm").classList.add('hide');
            document.getElementById("Otpcredential").classList.add('hide');
            document.getElementById("sendMessageBox").classList.remove('hide');
        } else {
            document.getElementById("Otpcredential").classList.add('hide');
            document.getElementById("LoginForm").classList.remove('hide');
            document.getElementById("sendMessageBox").classList.add('hide');
        }
        chrome.storage.local.get("countryCode", ({
            countryCode
        }) => {
            $("#countryCode").val(countryCode);
        });
        chrome.storage.local.get("FileTemplateSend", (FileTemplateSend) => {
            if (FileTemplateSend.FileTemplateSend != null && FileTemplateSend.FileTemplateSend != '') {
                FileTemplateSend = JSON.parse(FileTemplateSend.FileTemplateSend);
                fileBase = FileTemplateSend.values;
                $("#TemplateImage").children().remove();
                $("#TemplateImage").append(`<div class="py-2"><img class='img-fluid' width="150"  style="border: 1px solid #e1e1e1;" src="` + fileBase + `" /><span id="removeTemplateImage" style="cursor:pointer;font-size: 8px;width: 3px;height: 3px;background: #333;color: #FFF;border-radius: 50%;text-align: center;padding: 2px 4px;position: relative;top: -2px;margin-left: 5px;">X</span></div>`);
            }
        });
        chrome.storage.local.get("ExcelFile", (ExcelFile) => {
            if (ExcelFile.ExcelFile != null && ExcelFile.ExcelFile != '') {
                ExcelFile = JSON.parse(ExcelFile.ExcelFile);
                ExcelVal = ExcelFile.values;
                document.getElementById("FileName").innerHTML = ExcelFile.name + "<span id='removeFile' class='removeFileExcel'>X</span>";
                var keys = Object.keys(ExcelFile.values[0]);
                var selectHTML = "";
                selectHTML += "<label>Please select the mobile numbers column. :</label>";
                selectHTML += "<select class='form-control' id='selection-val'>";
                for (var x = 0; x < keys.length; x++) {
                    selectHTML += "<option value=" + keys[x] + ">" + keys[x] + "</option>";
                }
                selectHTML += "</select>";
                mapColumn.classList.remove("hide");
                mapColumn.innerHTML = selectHTML;

                $("#selection-val option:contains('mobile')").prop('selected', true);
                $("#selection-val option:contains('number')").prop('selected', true);
                $("#selection-val option:contains('Mobile')").prop('selected', true);
                $("#selection-val option:contains('Number')").prop('selected', true);
                $("#selection-val option:contains('Contact')").prop('selected', true);
                $("#selection-val option:contains('contact')").prop('selected', true);

                var variableSuggest = document.getElementById("variableSuggest");
                var variableSuggestHTML = "";
                for (var x = 0; x < keys.length; x++) {
                    variableSuggestHTML += "<div class='variable'>" + keys[x] + "</div>";
                }

                variableSuggest.innerHTML = variableSuggestHTML;
            } else {
                ExcelFile.ExcelFile = "";
                ExcelVal = [];
            }
        });

        chrome.storage.local.get("imageAttachment", ({
            imageAttachment
        }) => {
            if (imageAttachment) {
                $("#attachment").trigger('click');
            }
        });
        chrome.storage.local.get("quickbuttons", ({
            quickbuttons
        }) => {
            if (quickbuttons) {
                $("#quickbuttons").trigger('click');
            }
        });
        chrome.storage.local.get("AttachFiles", (AttachFiles) => {
            if (AttachFiles.AttachFiles != null && AttachFiles.AttachFiles != '') {
                AttachFiles = JSON.parse(AttachFiles.AttachFiles);
                AttachFiles = AttachFiles.values;
                Files = AttachFiles;
                if (Files.length == 0) {
                    $("#fileList").addClass("hide");
                } else {
                    $("#fileList").removeClass("hide");
                }
                if ($("#attachment").prop('checked')) {
                    var selectHTML = "";
                    for (var y = 0; y < AttachFiles.length; y++) {
                        // if (Files[y].fileSize > 2000000) {
                        //     $("#alertFile").removeClass("hide");
                        //     showAlertFile = true;
                        // } else {
                        //     if (!showAlertFile) {
                        //         $("#alertFile").addClass("hide");
                        //     }
                        // }
                        selectHTML += "<div class='mb-2'>" + AttachFiles[y].fileName + " <span data-delete='" + y + "' class='deleteFile' style='cursor:pointer;float: right;font-size: 8px;width: 16px;height: 18px;background: #333;color: #FFF;border-radius: 50%;text-align: center;padding: 4px;'>X</div>";
                        selectHTML += "<div class='mb-2'><textarea name='fileList' class='form-control fileListCaption' data-id='" + y + "' placeholder='Add Caption' id='fileList" + y + "'>" + AttachFiles[y].caption + "</textarea></div>";
                    }
                    selectHTML += "<div id='addMoreFile' class='btn btn-success btn-sm px-3'>Add More</div>";
                    document.getElementById("fileList").innerHTML = selectHTML;
                };
            }
        });
        chrome.storage.local.get("bt", ({
            bt
        }) => {
            $("#bt").val(bt);
            if (!bt) {
                chrome.storage.local.set({
                    "bt": '1'
                });
                $("#bt").val(1);
            }
        });
        chrome.storage.local.get("mis", ({
            mis
        }) => {
            $("#mis").val(mis);
            if (!mis) {
                chrome.storage.local.set({
                    "mis": '3'
                });
                $("#mis").val(3);
            }
        });
        chrome.storage.local.get("QuickCall", ({
            QuickCall
        }) => {
            $("#QuickCall").val(QuickCall);
        });
        chrome.storage.local.get("QuickURL", ({
            QuickURL
        }) => {
            $("#QuickURL").val(QuickURL);
        });
        chrome.storage.local.get("at", ({
            at
        }) => {
            $("#at").val(at);
            if (!at) {
                chrome.storage.local.set({
                    "at": '20'
                });
                $("#at").val(20);
            }
        });
        chrome.storage.local.get("mim", ({
            mim
        }) => {
            $("#mim").val(mim);
            if (!mim) {
                chrome.storage.local.set({
                    "mim": '1'
                });
                $("#mim").val(1);
            }
        });
        chrome.storage.local.get("commaSeprated", ({
            commaSeprated
        }) => {
            $("#commaSeprated").val(commaSeprated);
        });
        chrome.storage.local.get("QuickCallLabel", ({
            QuickCallLabel
        }) => {
            $("#QuickCallLabel").val(QuickCallLabel);
        });
        chrome.storage.local.get("QuickURLLabel", ({
            QuickURLLabel
        }) => {
            $("#QuickURLLabel").val(QuickURLLabel);
        });
        chrome.storage.local.get("message", ({
            message
        }) => {
            $("#message").val(message);
        });
        chrome.storage.local.get("isActivatedApi", ({
            isActivatedApi
        }) => {
            if (isActivatedApi) {
                $(".alert").hide();
                // $(".activated").addClass("bg-success");
                $("#LoginLogout").addClass('logoutBtn');
                chrome.storage.local.set({
                    'isDemo': false
                });
            }else if(isActivatedApi == false){
                document.getElementById("LoginBox").classList.add('hide');
                document.getElementById("sendMessageBox").classList.remove('hide');
                $(".activated").text("Demo Plan");
                $("#LoginLogout").text("logout");
                $("#LoginLogout").addClass('logoutBtn');
                chrome.storage.local.set({
                    'isDemo': true
                });
            } else {
                document.getElementById("LoginBox").classList.add('hide');
                document.getElementById("sendMessageBox").classList.remove('hide');
                $(".activated").text("Free Plan");
                $("#LoginLogout").text("Login");
                chrome.storage.local.set({
                    'isDemo': true
                });
            }
        });
        $("#fromNumber").keypress(function(event) {
            if (event.which == 32 || event.which != 8 && isNaN(String.fromCharCode(event.which))) {
                event.preventDefault();
            }
        })
        $(".iconsemoji").click(function() {
            $('.emojis').toggle();
        })
        $(".emojis").disMojiPicker();
        $(".emojis").picker(emoji => insertAtCaret('message', emoji));
        twemoji.parse(document.body);
        $(".emojis").mouseleave(function() {
            $('.emojis').hide();
        });

        chrome.storage.local.get("Automation", ({
            Automation
        }) => {
            if(Automation == 2){
                $("#textTyping").prop("checked",true);
            }else{
                $("#turboSpeed").prop("checked",true);
            }
        });
    }
    $("#bt").change(function() {
        chrome.storage.local.set({
            'bt': "1"
        });
    });
    $("#mis").change(function() {
        chrome.storage.local.set({
            'mis': $(this).val()
        });
    });
    $("#at").change(function() {
        chrome.storage.local.set({
            'at': $(this).val()
        });
    });
    $("#mim").change(function() {
        chrome.storage.local.set({
            'mim': $(this).val()
        });
    });
    $("#QuickCallLabel").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'QuickCallLabel': $(this).val()
        });
    });
    $("#QuickURLLabel").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'QuickURLLabel': $(this).val()
        });
    });
    $("#commaSeprated").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'commaSeprated': $(this).val()
        });
    });
    $("#message").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'message': $(this).val()
        });
    });
    $("#countryCode").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'countryCode': $(this).val()
        });
    });
    $("#QuickCall").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'QuickCall': $(this).val()
        });
    });

    $("#QuickURL").on('blur keypress keyup keydown', function() {
        chrome.storage.local.set({
            'QuickURL': $(this).val()
        });
    });

    $("#commaSeprated").bind({
        paste: function() {
            chrome.storage.local.set({
                'commaSeprated': $("#commaSeprated").val()
            });
        },
    });
    $("#message").bind({
        paste: function() {
            chrome.storage.local.set({
                'message': $("#message").val()
            });
        },
    });
    document.getElementById("Exportgroup").addEventListener("click", function(e) {
        $("#groupGrab").trigger("click");
        setTimeout(function() {
            $("#headerTable").table2excel({
                exclude: ".noExl",
                name: "Data",
                filename: "group",
                fileext: ".xls",
                columns: [0, 1, 2] // export first three columns
            });
        }, 500);
    });
    chrome.runtime.onMessage.addListener(
        (request, sender, sendResponse) => {
            if (request.message === "groupContact") {
                chrome.storage.local.get("groupContact", ({
                    groupContact
                }) => {
                    var value = "";
                    if (groupContact != null) {
                        document.getElementById("countNumber").innerHTML = groupContact.length - 1;
                        for (var i = 0; i < groupContact.length - 1; i++) {
                            if (i == (groupContact.length - 2)) {
                                value += groupContact[i].user;
                            } else {
                                value += groupContact[i].user + ",";
                            }
                        }
                    }
                    $("#commaSeprated").val(value);
                    chrome.storage.local.set({
                        'commaSeprated': value
                    });
                    chrome.storage.local.get("groupContactName", ({
                        groupContactName
                    }) => {
                        for (var i = 0; i < groupContactName.length - 1; i++) {
                            contactVal.push({
                                "Contact Name": groupContactName[i]
                            });
                        }
                        var tableMake = document.getElementsByClassName('tableMake')[0];
                        document.getElementsByClassName('tableMake')[0].innerHTML = "";
                        var tbl = document.createElement('table');
                        tbl.id = "headerTable";
                        tbl.className = "table table-bordered";
                        tbl.style.width = '100%';
                        tbl.setAttribute('border', '1');
                        var thad = document.createElement('thead');
                        var th1 = document.createElement('th');
                        var tr2 = document.createElement('tr');
                        var th2 = document.createElement('th');
                        th1.appendChild(document.createTextNode("Number"))
                        th2.appendChild(document.createTextNode("Name"))
                        tr2.appendChild(th1);
                        tr2.appendChild(th2);
                        thad.appendChild(tr2);
                        var tbdy = document.createElement('tbody');
                        for (var i = 0; i < groupContactName.length; i++) {
                            var tr = document.createElement('tr');
                            for (var j = 0; j < 1; j++) {
                                var td1 = document.createElement('td');
                                var td2 = document.createElement('td');
                                td1.appendChild(document.createTextNode(groupContact[i].user))
                                td2.appendChild(document.createTextNode(groupContactName[i].replace(/[^a-zA-Z ]/g, '')))
                                console.log(groupContactName[i].replace(/[^a-zA-Z ]/g, ''));
                                tr.appendChild(td1);
                                tr.appendChild(td2);
                            }
                            tbdy.appendChild(tr);
                        }
                        tbl.appendChild(thad);
                        tbl.appendChild(tbdy);
                        tableMake.appendChild(tbl)
                    });
                    var variableSuggest = document.getElementById("variableSuggest");
                    var variableSuggestHTML = "";
                    variableSuggestHTML += "<div class='variable'>Contact Name</div>";
                    variableSuggest.innerHTML = variableSuggestHTML;
                });
            }

            if (request.message === "error") {
                chrome.storage.local.get("error", ({
                    error
                }) => {
                    swal(error);
                })
            }
        });

    function insertAtCaret(areaId, text) {
        var txtarea = document.getElementById(areaId);
        if (!txtarea) {
            return;
        }

        var scrollPos = txtarea.scrollTop;
        var strPos = 0;
        var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
            "ff" : (document.selection ? "ie" : false));
        if (br == "ie") {
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart('character', -txtarea.value.length);
            strPos = range.text.length;
        } else if (br == "ff") {
            strPos = txtarea.selectionStart;
        }
        var front = (txtarea.value).substring(0, strPos);
        var back = (txtarea.value).substring(strPos, txtarea.value.length);
        txtarea.value = front + text + back;
        strPos = strPos + text.length;
        if (br == "ie") {
            txtarea.focus();
            var ieRange = document.selection.createRange();
            ieRange.moveStart('character', -txtarea.value.length);
            ieRange.moveStart('character', strPos);
            ieRange.moveEnd('character', 0);
            ieRange.select();
        } else if (br == "ff") {
            txtarea.selectionStart = strPos;
            txtarea.selectionEnd = strPos;
            txtarea.focus();
        }

        txtarea.scrollTop = scrollPos;
    }
    chrome.tabs.query({
        active: true,
        lastFocusedWindow: true
    }, tabs => {
        $("#username").val(localStorage.getItem("username"));
        $("#password").val(localStorage.getItem("password"));
        $("#email").val(localStorage.getItem("email"));
        $("#fromNumber").val(localStorage.getItem("fromNumber"));
        if (tabs.length > 0) {
            let url = tabs[0].url;
            if (url != "https://web.whatsapp.com/") {
                chrome.tabs.create({
                    active: true,
                    url: "https://web.whatsapp.com/"
                })
            }
        }
    });
    $("#username").keyup(function(e) {
        localStorage.setItem("username", e.currentTarget.value);
    })
    $("#password").keyup(function(e) {
        localStorage.setItem("password", e.currentTarget.value);
    })
    $("#email").keyup(function(e) {
        localStorage.setItem("email", e.currentTarget.value);
    })
    $("#fromNumber").keyup(function(e) {
        e.currentTarget.value = e.currentTarget.value.replace(/[^0-9]/gi, '');
        localStorage.setItem("fromNumber", e.currentTarget.value);
    })
    $(function() {
        $('#imgTooltip').tooltip({
            template: '<div class="tooltip tooltip-custom"><div class="imgTemplatehover"><img src="https://whatso.net/img/buttonTemplate.jpeg" width="290" height="290" style="border:1px solid #888"/></div><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
        })
        $('[data-toggle="tooltip"]').tooltip();
    })
    document.getElementById("input-file").addEventListener("change", readTextFile);
    document.getElementById("FileSend").addEventListener("change", fileTosend);
    document.getElementById("attachment").addEventListener("change", showFileType);
    document.getElementById("quickbuttons").addEventListener("change", showButtonsRadio);

    async function showButtonsRadio(e) {
        $("#attachment").prop('checked', false);
        $("#listButton").prop('checked', false);
        document.getElementById("showFileRadio").classList.add('hide');
        // document.getElementById("showlistButtonRadio").classList.add('hide');
        if (e.currentTarget.checked) {
            document.getElementById("showButtonsRadio").classList.remove('hide');
            document.getElementById("fileList").classList.add('hide');
        } else {
            document.getElementById("showButtonsRadio").classList.add('hide');
        }
    }
    document.getElementById("sendmessage").addEventListener("click", function(e) {
        e.preventDefault();
        document.getElementById("sendmessage").disabled = true;
        setTimeout(function() {
            document.getElementById("sendmessage").disabled = false;
        }, 5000)
        var file = document.getElementById("input-file").value;
        var commaSeprated = document.getElementById("commaSeprated").value;
        var message = document.getElementById("message").value;
        if (ExcelVal != null && ExcelVal != "") {
            sendmessage();
        } else if (commaSeprated != null && commaSeprated != "") {
            sendmessage();
        } else if (message != null && message != "") {
            sendmessage();
        } else {
            alert('Please select contacts excel')
        }
    });
    document.getElementById("groupGrab").addEventListener("click", function(e) {
        chrome.windows.getCurrent(w => {
            chrome.tabs.query({
                active: true,
                windowId: w.id
            }, tabs => {
                const tabId = tabs[0].id;
                chrome.scripting.executeScript({
                    target: {
                        tabId: tabId
                    },
                    function: async() => {
                        try {
                            const GROUP_GRAB = "GOT_GROUP_GRAB";
                            const GROUP_GRAB_CONTACT = "GOT_GROUP_GRAB_CONTACT";
                            var node = document.querySelectorAll('[data-id]')[0].getAttribute("data-id");
                            if (node) {
                                var id = node.split("_")[1];
                                var idType = id.split('@');
                                if (idType[1] == "g.us") {
                                    document.dispatchEvent(new CustomEvent(GROUP_GRAB, {
                                        detail: id
                                    }));
                                    document.addEventListener(GROUP_GRAB_CONTACT, function(e) {
                                        debugger;
                                        chrome.storage.local.set({
                                            "groupContact": e.detail[0].data
                                        });
                                        chrome.storage.local.set({
                                            "groupContactName": e.detail[0].name
                                        });
                                        chrome.runtime.sendMessage({
                                            message: "groupContact"
                                        }, (response) => {});
                                    });
                                } else {
                                    chrome.storage.local.set({
                                        "error": "This chat is not group"
                                    });
                                    chrome.runtime.sendMessage({
                                        message: "error"
                                    }, (response) => {});
                                }
                            } else {
                                chrome.storage.local.set({
                                    "error": "Please open group"
                                });
                                chrome.runtime.sendMessage({
                                    message: "error"
                                }, (response) => {});
                            }
                        } catch (ex) {
                            chrome.storage.local.set({
                                "error": "Please open group"
                            });
                            chrome.runtime.sendMessage({
                                message: "error"
                            }, (response) => {});
                        }
                    }
                });
            });
        });
    });
    document.getElementById("goToEmail").addEventListener("click", function(e) {
        document.getElementById("Otpcredential").classList.add('hide');
        document.getElementById("LoginForm").classList.remove('hide');
        document.getElementById("goToEmail").classList.add('hide');
    });
    $('#fileList').on('click', '#addMoreFile', function(e) {
        document.getElementById("FileSend").click();
    });
    $(".appendListItem").click(function() {
        $("#dynamicList").append('<div class="row mb-2"><div class="col pr-0"><input type="text" class="form-control" id="List' + ($("#dynamicList").children().length + 1) + '"></div><div class="col-auto"><button class="btn btn-danger deleteListItem">-</button></div></div>');
    })
    $('#dynamicList').on('click', ".deleteListItem", function() {
        $(this).parent().parent().remove();
    })
    $('#fileList').on('click', '.deleteFile', function(e) {
        Files.splice(e.currentTarget.dataset.delete, 1);
        var selectHTML = "";
        for (var y = 0; y < Files.length; y++) {
            // if (!showAlertFile) {
            //     if (Files[y].fileSize > 2000000) {
            //         $("#alertFile").removeClass("hide");
            //         showAlertFile = true;
            //     } else {
            //         $("#alertFile").addClass("hide");
            //     }
            // }
            selectHTML += "<div class='mb-2'>" + Files[y].fileName + " <span data-delete='" + y + "' class='deleteFile' style='cursor:pointer;float: right;font-size: 8px;width: 16px;height: 18px;background: #333;color: #FFF;border-radius: 50%;text-align: center;padding: 4px;'>X</div>";
            selectHTML += "<div class='mb-2'><textarea name='fileList' value='" + Files[y].caption + "' class='form-control fileListCaption' data-id='" + y + "' placeholder='Add Caption' id='fileList" + y + "'></textarea></div>";
        }
        if (Files.length == 0) {
            $("#alertFile").addClass("hide");
        }
        selectHTML += "<div id='addMoreFile' class='btn btn-success mt-2'>Add More</div>";
        document.getElementById("fileList").innerHTML = selectHTML;
        if (Files.length == 0) {
            $("#addMoreFile").remove();
            $("#FileSend").val('');
            $("#showFileRadio").removeClass("hide");
            $("#fileList").addClass("hide");
        }
        chrome.storage.local.set({
            "AttachFiles": `{ "values" : ` + JSON.stringify(Files) + `}`
        });
        showAlertFile = false;
    });
    $('#fileList').on('keyup', '.fileListCaption', function(e) {
        Files[e.currentTarget.dataset.id].caption = e.currentTarget.value;
        chrome.storage.local.set({
            "AttachFiles": `{ "values" : ` + JSON.stringify(Files) + `}`
        });
    })
    async function fileTosend(e) {
        var fileName = e.currentTarget.files[0].name;
        var fileSize = e.currentTarget.files[0].size;
        fileBase = await toBase64(e.currentTarget.files[0]).then(data => {
            return data;
        });
        Files.push({
            "file": fileBase,
            "fileSize": fileSize,
            "fileName": fileName,
            "caption": ""
        });
        var selectHTML = "";
        for (var y = 0; y < Files.length; y++) {
            // if (Files[y].fileSize > 2000000) {
            //     $("#alertFile").removeClass("hide");
            //     showAlertFile = true;
            // } else {
            //     if (!showAlertFile) {
            //         $("#alertFile").addClass("hide");
            //     }
            // }
            selectHTML += "<div class='mb-2'>" + Files[y].fileName + " <span data-delete='" + y + "' class='deleteFile' style='cursor:pointer;float: right;font-size: 8px;width: 16px;height: 18px;background: #333;color: #FFF;border-radius: 50%;text-align: center;padding: 4px;'>X</div>";
            selectHTML += "<div class='mb-2'><textarea name='fileList' value='" + Files[y].caption + "' class='form-control fileListCaption' data-id='" + y + "' placeholder='Add Caption' id='fileList" + y + "'></textarea></div>";
        }
        selectHTML += "<div id='addMoreFile' class='btn btn-success btn-sm px-3'>Add More</div>";
        document.getElementById("fileList").innerHTML = selectHTML;
        $("#fileList").removeClass("hide");
        $("#showFileRadio").addClass("hide");
        chrome.storage.local.set({
            "AttachFiles": `{ "values" : ` + JSON.stringify(Files) + `}`
        });
    }
    async function showFileType(e) {
        $("#quickbuttons").prop('checked', false);
        // $("#listButton").prop('checked', false);
        document.getElementById("showButtonsRadio").classList.add('hide');
        if (Files.length == 0) {
            // document.getElementById("showlistButtonRadio").classList.add('hide');
            if (e.currentTarget.checked) {
                document.getElementById("showFileRadio").classList.remove('hide');
                document.getElementById("fileList").classList.remove('hide');
            } else {
                document.getElementById("showFileRadio").classList.add('hide');
                document.getElementById("fileList").classList.add('hide');
            }
        } else {
            if (e.currentTarget.checked) {
                var selectHTML = "";
                for (var y = 0; y < Files.length; y++) {
                    selectHTML += "<div class='mb-2'>" + Files[y].fileName + " <span data-delete='" + y + "' class='deleteFile' style='cursor:pointer;float: right;font-size: 8px;width: 16px;height: 18px;background: #333;color: #FFF;border-radius: 50%;text-align: center;padding: 4px;'>X</div>";
                    selectHTML += "<div class='mb-2'><textarea name='fileList' value='" + Files[y].caption + "' class='form-control fileListCaption' data-id='" + y + "' placeholder='Add Caption' id='fileList" + y + "'></textarea></div>";
                }
                selectHTML += "<div id='addMoreFile' class='btn btn-success btn-sm px-3'>Add More</div>";
                document.getElementById("fileList").innerHTML = selectHTML;
                chrome.storage.local.set({
                    "AttachFiles": `{ "values" : ` + JSON.stringify(Files) + `}`
                });
                document.getElementById("fileList").classList.remove('hide');
            } else {
                document.getElementById("showFileRadio").classList.add('hide');
                document.getElementById("fileList").classList.add('hide');
            }
        }
    }
    docReady(async function() {
        chrome.storage.local.get("emailId", ({
            emailId
        }) => {
            chrome.storage.local.get("username", ({
                username
            }) => {
                chrome.storage.local.get("password", ({
                    password
                }) => {
                    chrome.storage.local.get("fromNumber", ({
                        fromNumber
                    }) => {
                        chrome.storage.local.get("isActivatedApi", async({
                            isActivatedApi
                        }) => {
                            if (!emailId && !username && !password && isActivatedApi != undefined) {
                                // chrome.storage.local.get("isDeactivate", async({ isDeactivate }) => {
                                const rawResponse = await fetch('https://webapi.whatso.net/api/UnAuthorized/get-whatsapp-messages', {
                                    method: 'POST',
                                    headers: {
                                        'Accept': 'application/json',
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify({
                                        "emailId": emailId,
                                        "key": username,
                                        "FromNumber": fromNumber,
                                        "secret": password,
                                        "apiMode": 2
                                    })
                                });
                                const content = await rawResponse.json();
                                // });
                            }
                            $(".activated").removeClass("demo");
                            if (emailId && username && password) {
                                if (!isActivatedApi) {
                                    $(".demo").removeClass("hide");
                                    $(".activated").text("Demo Plan");
                                    $(".activated").addClass("demo");
                                }
                                document.getElementById("LoginBox").classList.add('hide');
                                document.getElementById("sendMessageBox").classList.remove('hide');
                            }
                        });
                    });
                });
            });
        });
    });
    $('#TemplateImage').on('click', "#removeTemplateImage", function() {
        $(this).prev().remove();
        $(this).remove();
        $("#FileTemplateSend").val('');
        chrome.storage.local.set({
            "FileTemplateSend": ''
        });
    })
    $("#FileTemplateSend").on("change", async function(e) {
        if (e.currentTarget.files.length > 0) {
            fileBase = await toBase64(e.currentTarget.files[0]).then(data => {
                return data;
            });
        }
        chrome.storage.local.set({
            "FileTemplateSend": `{ "name" : "` + e.currentTarget.files[0].name + `" , "values" : ` + JSON.stringify(fileBase) + `}`
        });
        $("#TemplateImage").children().remove();
        $("#TemplateImage").append(`<div class="py-2"><img class='img-fluid' width="150" src="` + fileBase + `" style="border: 1px solid #e1e1e1;"/><span id="removeTemplateImage" style="cursor:pointer;font-size: 8px;width: 3px;height: 3px;background: #333;color: #FFF;border-radius: 50%;text-align: center;padding: 2px 4px;position: relative;top: -2px;margin-left: 5px;">X</span></div>`);
    })
    $("#LoginLogout").on('click', function() {
        if ($(this).hasClass('logoutBtn')) {
            chrome.storage.local.clear(function() {
                var error = chrome.runtime.lastError;
                if (error) {
                    console.error(error);
                }
                // do something more
            });
            chrome.storage.local.clear(); // callback is optional
            location.reload();
        } else if (localStorage.getItem("email") != null && localStorage.getItem("email") != "") {
            document.getElementById("sendMessageBox").classList.add('hide');
            document.getElementById("LoginBox").classList.remove('hide');
            document.getElementById("LoginForm").classList.add('hide');
            document.getElementById("goToEmail").classList.remove('hide');
            document.getElementById("Otpcredential").classList.remove('hide');
        } else {
            document.getElementById("LoginBox").classList.remove('hide');
            document.getElementById("LoginForm").classList.remove('hide');
            document.getElementById("Otpcredential").classList.add('hide');
            document.getElementById("sendMessageBox").classList.add('hide');
        }
    });
    $("#attachment").change(function() {
        if ($(this).prop('checked')) {
            chrome.storage.local.set({
                'imageAttachment': true
            });
        } else {
            chrome.storage.local.set({
                'imageAttachment': false
            });
        }
        chrome.storage.local.set({
            'quickbuttons': false
        });
    })
    $("#quickbuttons").change(function() {
        if ($(this).prop('checked')) {
            chrome.storage.local.set({
                'quickbuttons': true
            });
        } else {
            chrome.storage.local.set({
                'quickbuttons': false
            });
        }
        chrome.storage.local.set({
            'imageAttachment': false
        });
    })
    $('#FileName').on('click', '#removeFile', function(e) {
        document.getElementById("input-file").value = "";
        ExcelVal = [];
        $("#FileName").text("");
        $("#FileName").children().remove();
        $("#mapColumn").addClass("hide");
        $("#countNumber").text("00");
        $("#mapColumn").children().remove();
        $("#variableSuggest").html('');
        chrome.storage.local.set({
            "ExcelFile": ""
        })
    });

    $("#commaSeprated").on('keyup', function(e){
        if(e.code == "Comma"){
            var commaSeprated = document.getElementById("commaSeprated").value;
            commaSepratedValue = commaSeprated.split(',');
            $("#countNumber").text(commaSepratedValue.length - 1);
        };
    });
    $("#editSetting").on('click', function(e){
        $("#mis").removeAttr('disabled');
        $("#mim").removeAttr('disabled');
        $("#at").removeAttr('disabled');
        $("input[name='typeAutomation']").removeAttr('disabled');
    });

    $("#saveSetting").click(function(){
        chrome.storage.sync.set({
            "mis": $("#mis").val()
        })
        chrome.storage.sync.set({
            "mim": $("#mis").val()
        })
        chrome.storage.sync.set({
            "at": $("#mis").val()
        })
        chrome.storage.local.set({
            "Automation": $("input[name='typeAutomation']:checked").val()
        })
        
        $("#mis").attr('disabled',true);
        $("#mim").attr('disabled',true);
        $("#at").attr('disabled',true);
        $("input[name='typeAutomation']").attr('disabled',true);
    });
    $("#DiscardBtn").click(function(){
        $("#mis").attr('disabled',true);
        $("#mim").attr('disabled',true);
        $("#at").attr('disabled',true);
        $("input[name='typeAutomation']").attr('disabled',true);
    });
    $("#commaSeprated").on('focusout', function(e){
        var commaSeprated = document.getElementById("commaSeprated").value;
        if(commaSeprated == ''){
            $("#countNumber").text("00");
        }else{
            commaSepratedValue = commaSeprated.split(',');
            $("#countNumber").text(commaSepratedValue.length);
        }
    });
    function docReady(fn) {

        // see if DOM is already available
        if (document.readyState === "complete" || document.readyState === "interactive") {
            // call on next available tick
            setTimeout(fn, 1);
        } else {
            document.addEventListener("DOMContentLoaded", fn);
        }
    }

    function replaceKeys(object) {
        Object.keys(object).forEach(function(key) {
            var newKey = key.replace(/\s+/g, '');
            if (object[key] && typeof object[key] === 'object') {
                replaceKeys(object[key]);
            }
            if (key !== newKey) {
                object[newKey] = object[key];
                delete object[key];
            }
        });
    }

    function readTextFile(e) {
        var file = e.target.files[0];
        // input canceled, return
        if (!file) return;
        chrome.storage.sync.set({
            "yourBody": "myBody"
        }, function() {
            //  A data saved callback omg so fancy
        });
        document.getElementById("FileName").innerHTML = document.getElementById("input-file").value.replace('C:\\fakepath\\', '') + "<span id='removeFile' class='removeFileExcel'>X</span>";
        var FR = new FileReader();
        FR.onload = function(e) {
            var data = new Uint8Array(e.target.result);
            var workbook = XLSX.read(data, {
                type: 'array'
            });
            var firstSheet = workbook.Sheets[workbook.SheetNames[0]];

            // header: 1 instructs xlsx to create an 'array of arrays'
            ExcelVal = XLSX.utils.sheet_to_json(firstSheet, {
                header: 0,
                blankrows: false
            });
            replaceKeys(ExcelVal);
            document.getElementById('countNumber').innerHTML = ExcelVal.length;
            chrome.storage.local.set({
                'ExcelVal': ExcelVal
            });
            chrome.storage.local.set({
                "ExcelFile": `{ "name" : "` + file.name + `" , "values" : ` + JSON.stringify(ExcelVal) + `}`
            });
            var mapColumn = document.getElementById("mapColumn");
            var keys = Object.keys(ExcelVal[0]);
            var selectHTML = "";
            selectHTML += "<label>Please select the mobile numbers column. :</label>";
            selectHTML += "<select class='form-control' id='selection-val'>";
            for (var x = 0; x < keys.length; x++) {
                selectHTML += "<option value=" + keys[x] + ">" + keys[x] + "</option>";
            }
            selectHTML += "</select>";
            mapColumn.classList.remove("hide");
            mapColumn.innerHTML = selectHTML;

            $("#selection-val option:contains('mobile')").prop('selected', true);
            $("#selection-val option:contains('number')").prop('selected', true);
            $("#selection-val option:contains('Mobile')").prop('selected', true);
            $("#selection-val option:contains('Number')").prop('selected', true);
            $("#selection-val option:contains('Contact')").prop('selected', true);
            $("#selection-val option:contains('contact')").prop('selected', true);

            var variableSuggest = document.getElementById("variableSuggest");
            var variableSuggestHTML = "";
            for (var x = 0; x < keys.length; x++) {
                variableSuggestHTML += "<div class='variable'>" + keys[x] + "</div>";
            }

            variableSuggest.innerHTML = variableSuggestHTML;
        };
        FR.readAsArrayBuffer(file);
    }

    function insertAtCursor(input, textToInsert) {
        // get current text of the input
        const value = input.value;

        // save selection start and end position
        const start = input.selectionStart;
        const end = input.selectionEnd;

        // update the value with our text inserted
        input.value = value.slice(0, start) + textToInsert + value.slice(end);

        // update cursor to be at the end of insertion
        input.selectionStart = input.selectionEnd = start + textToInsert.length;
    }
    $('#variableSuggest').on('click', '.variable', function(e) {
        insertAtCursor(document.getElementById("message"), '#' + e.target.innerHTML + '#');
        for (var i = 0; i < document.getElementsByClassName("fileListCaption").length; i++) {
            insertAtCursor(document.getElementsByClassName("fileListCaption")[i], '#' + e.target.innerHTML + '#');
            Files[i].caption = '#' + e.target.innerHTML + '#';
        }
        document.getElementById("message").focus();
    });
    function checkInternet() {
        if (document.getElementsByClassName("_2XcXo").length > 0) {
            return true;
        }
        if (document.getElementsByClassName("_1zOyO").length > 0) {
            return true;
        }
        if (document.getElementsByClassName("_30oB1").length > 0) {
            return true;
        }
        if (document.getElementsByClassName("_2Zdgs").length > 0) {
            return true;
        }
    }

    function checkLogin() {
        if (document.getElementsByClassName("_30yMe").length > 0) {
            alert('Please scan you QR to start extension')
        }
    }

    function setLogo() {
        if (document.getElementsByClassName("_3GlyB")[0]) {
            document.getElementsByClassName("_3GlyB")[0].innerHTML = '<img src="https://whatsocdn.s3.us-west-2.amazonaws.com/images/whatso-latest-logo.png" height="40" />';
        }
        return true;
    }

    document.querySelector("#LoginForm").addEventListener("submit", async function(e) {
        e.preventDefault();
        // if ($("#checkemail").prop("checked")) {
        const emailId = e.currentTarget[0].value;
        const rawResponseMessages = await fetch('https://whatso.net/svc.asmx/GetOtpDetails?Email=' + emailId + '&source=1', {
            method: 'GET',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        });
        const contents = await rawResponseMessages.json();
        if (contents.Response == 1) {
            $("#sendCredenital").append('<div class="alert alert-success mt-3">OTP is sent.</div>');
            setTimeout(function() {
                $(".alert").remove();
                document.getElementById("Otpcredential").classList.remove('hide');
                document.getElementById("LoginForm").classList.add('hide');
                document.getElementById("goToEmail").classList.remove('hide');
            }, 3000)
        } else {
            alert(contents.Message)
        }
        // }

    });
    document.querySelector("#Otpcredential").addEventListener("submit", function(e) {
        e.preventDefault();
        chrome.windows.getCurrent(w => {
            chrome.tabs.query({
                active: true,
                windowId: w.id
            }, tabs => {
                const tabURL = tabs[0].url;
                if (tabURL !== "https://web.whatsapp.com/") {
                    chrome.tabs.update({
                        active: true,
                        url: "https://web.whatsapp.com/"
                    })
                }

            });
        });
        (async() => {
            const otp = e.currentTarget[0].value;
            const emailId = $("#email").val();
            const rawResponse = await fetch('http://webapi.whatso.net/api/UnAuthorized/get-plan', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    "emailId": emailId,
                    "otp": otp,
                    "password": "",
                    "username": "",
                    "isExtension": true
                })
            });
            const content = await rawResponse.json();
            if (content.loginLink != null) {
                if (content.responseStatusCode == '200') {
                    if (content.abandonedCartPurchasedPlan != null) {
                        chrome.storage.local.set({
                            "abandonedCartPurchasedPlan": content.abandonedCartPurchasedPlan
                        });
                    }
                    if (content.apiPurchasedPlan != null) {
                        chrome.storage.local.set({
                            "apiPurchasedPlan": content.apiPurchasedPlan
                        });
                    }
                    if (content.isAPIPurchased != null) {
                        chrome.storage.local.set({
                            "isAPIPurchased": content.isAPIPurchased
                        });
                    }
                    if (content.isAbandonedCartPurchased != null) {
                        chrome.storage.local.set({
                            "isAbandonedCartPurchased": content.isAbandonedCartPurchased
                        });
                    }
                    if (content.isSMSPurchased != null) {
                        chrome.storage.local.set({
                            "isSMSPurchased": content.isSMSPurchased
                        });
                    }
                    if (content.isWhatsoDesktopSoftwarePurchased != null) {
                        chrome.storage.local.set({
                            "isWhatsoDesktopSoftwarePurchased": content.isWhatsoDesktopSoftwarePurchased
                        });
                    }
                    if (content.loginLink != null) {
                        chrome.storage.local.set({
                            "loginLink": content.loginLink
                        });
                    }
                    if (content.smsPurchasedPlan != null) {
                        chrome.storage.local.set({
                            "smsPurchasedPlan": content.smsPurchasedPlan
                        });
                    }

                    if (content.whatsoDesktopSoftwarePurchasedPlan != null) {
                        chrome.storage.local.set({
                            "whatsoDesktopSoftwarePurchasedPlan": content.whatsoDesktopSoftwarePurchasedPlan
                        });
                    }
                    if (content.userName != null) {
                        chrome.storage.local.set({
                            'username': content.userName
                        });
                    }

                    if (content.password != null) {
                        chrome.storage.local.set({
                            'password': content.password
                        });
                    }
                    if (emailId != null) {
                        chrome.storage.local.set({
                            'emailId': emailId
                        });
                    }
                    var value = content.isAPIPurchased;
                    value = (content.isAPIPurchased.toLowerCase() === 'true');
                    if (value) {
                        chrome.storage.local.set({
                            'isActivatedApi': true
                        });
                        chrome.storage.local.set({
                            'isDemo': false
                        });
                        $(".demo").addClass("hide");
                        $(".activated").removeClass("demo");
                        document.getElementById("LoginBox").classList.add('hide');
                        document.getElementById("sendMessageBox").classList.remove('hide');
                    } else {
                        chrome.storage.local.set({
                            'isActivatedApi': false
                        });
                        chrome.storage.local.set({
                            'isDemo': true
                        });
                        $(".demo").removeClass("hide");
                        $(".activated").text("DEMO");
                        $(".activated").addClass("demo");
                    }
                    location.reload();
                }
            } else {
                if (content.message != null) {
                    $("#Otpcredential").children().eq(0).append('<div class="alert alert-success mt-3">'+ content.message +'</div>');
                } else {
                    $("#Otpcredential").children().eq(0).append('<div class="alert alert-success mt-3">'+ content.validateOtpMesaage +'</div>');
                }
                setTimeout(function() {
                    $(".alert").remove();
                }, 3000)
            }
        })();
    });

    const toBase64 = file => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });

    async function sendmessage() {
        var ExcelLink = document.getElementById("selection-val");
        var attachment = document.getElementById("attachment").checked;
        var quickbuttons = document.getElementById("quickbuttons").checked;
        var typeAutomation = $('input[name="typeAutomation"]:checked').val();
        // var listButton = document.getElementById("listButton").checked;
        var listButton = false;
        var file = document.getElementById("input-file").value;
        var commaSeprated = document.getElementById("commaSeprated").value;
        var message = document.getElementById("message").value;
        chrome.storage.local.set({
            "reportMessage": message
        });
        chrome.storage.local.set({
            "messagesApi": ""
        });
        chrome.storage.local.set({
            "messagesFileApi": ""
        });
        // var QuickReply = document.getElementById('QuickReply').value;
        var QuickCall = document.getElementById('QuickCall').value;
        var QuickURL = document.getElementById('QuickURL').value;
        var QuickCallLabel = document.getElementById('QuickCallLabel').value;
        var QuickURLLabel = document.getElementById('QuickURLLabel').value;
        var FileTemplateSend = document.getElementById('FileTemplateSend');
        var template = [];
        if (QuickCall) {
            template.push({
                "id": "1",
                "phoneNumber": QuickCall,
                "text": QuickCallLabel
            })
        }
        if (QuickURL) {
            template.push({
                "id": "1",
                "url": QuickURL,
                "text": QuickURLLabel
            })
        }
        var countryCode = document.getElementById('countryCode').value;
        if (file != null && file != "") {
            var selectionItem = document.getElementById('selection-val').value;
            if (countryCode == 91) {
                for (var i = 0; i < ExcelVal.length; i++) {
                    if (ExcelVal[i][selectionItem]) {
                        if (ExcelVal[i][selectionItem].toString().length < 12) {
                            ExcelVal[i][selectionItem] = countryCode + ExcelVal[i][selectionItem];
                        }
                    } else {
                        ExcelVal.splice(i, 1);
                    }
                }
            } else {
                for (var i = 0; i < ExcelVal.length; i++) {
                    ExcelVal[i][selectionItem] = countryCode + ExcelVal[i][selectionItem];
                }
            }
        } else if (ExcelLink != null && ExcelLink != "") {
            var selectionItem = document.getElementById('selection-val').value;
            if (countryCode == 91) {
                for (var i = 0; i < ExcelVal.length; i++) {
                    if (ExcelVal[i][selectionItem]) {
                        if (ExcelVal[i][selectionItem].toString().length < 12) {
                            ExcelVal[i][selectionItem] = countryCode + ExcelVal[i][selectionItem];
                        }
                    } else {
                        ExcelVal.splice(i, 1);
                    }
                }
            } else {
                for (var i = 0; i < ExcelVal.length; i++) {
                    ExcelVal[i][selectionItem] = countryCode + ExcelVal[i][selectionItem];
                }
            }
        } else if (commaSeprated != null && commaSeprated != "") {
            commaSepratedValue = commaSeprated.split(',');
            if (countryCode == 91) {
                for (var i = 0; i < commaSepratedValue.length; i++) {
                    if (commaSepratedValue[i].length < 12) {
                        commaSepratedValue[i] = countryCode + commaSepratedValue[i];
                    }
                }
            } else {
                for (var i = 0; i < commaSepratedValue.length; i++) {
                    commaSepratedValue[i] = countryCode + commaSepratedValue[i];
                }
            }
            if (countryCode != '' && countryCode != null) {
                $("#commaSeprated").val(commaSepratedValue.splice(','));
            }
            var commaSeprated = document.getElementById("commaSeprated").value;
        }
        if (quickbuttons) {
            if (file != null && file != "") {
                if (message != null && message != "") {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    chrome.storage.local.set({
                        "reportMessage": messageText
                    });
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if (ExcelVal[n][selectionItem]) {
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            } else {
                                ExcelVal.splice(i, 1);
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }
                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                "templateImage": fileBase,
                                "template": template,
                                'messageText': result
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: async() => {
                                    debugger;
                                    chrome.storage.local.get("messagesApi", async({
                                        messagesApi
                                    }) => {
                                        chrome.storage.local.get("reportMessage", async({
                                            reportMessage
                                        }) => {
                                            chrome.storage.local.get("bt", async({
                                                bt
                                            }) => {
                                                chrome.storage.local.get("mis", async({
                                                    mis
                                                }) => {
                                                    chrome.storage.local.get("at", async({
                                                        at
                                                    }) => {
                                                        chrome.storage.local.get("mim", async({
                                                            mim
                                                        }) => {
                                                            chrome.storage.local.get("isDemo", async({
                                                                isDemo
                                                            }) => {
                                                                var totalSuccess = 0;
                                                                var totalFail = 0;
                                                                const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                                                const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                                                const TEMPLATE_MESSAGE = "GOT_TEMPLATE_MESSAGE";
                                                                document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                                                    try {
                                                                        var result = e.detail.result;
                                                                        var ValidNumber = e.detail.number;
                                                                        tBodyhtml = "";
                                                                        tBodyhtml += "<tr>";
                                                                        if (result.numberExists) {
                                                                            totalSuccess++;
                                                                            tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                                        } else {
                                                                            totalFail++;
                                                                            tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                                        }
                                                                        tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                                        if (result.numberExists) {
                                                                            tBodyhtml += "<td> Sent </td>";
                                                                            tBodyhtml += "<td></td>";
                                                                        } else {
                                                                            tBodyhtml += "<td> Fail </td>";
                                                                            tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                                        }
                                                                        tBodyhtml += `</tr>`;
                                                                        document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                                                    } catch (ex) {
                                                                        console.log(ex);
                                                                    }
                                                                });
                                                                if (messagesApi != null && messagesApi.length > 0) {
                                                                    let wam = document.getElementById("whatsomessages");
                                                                    if (!wam) {
                                                                        var whatso = document.createElement("div");
                                                                        whatso.id = "whatsomessages";
                                                                        document.body.append(whatso);
                                                                        whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                        var html = "";
                                                                        html += "Please do not perform any activity during the whatso automation extension";
                                                                        document.getElementById("whatsomessages").append(html);
                                                                    }
                                                                    if (messagesApi.length > 0 && isDemo) {
                                                                        messagesApi.splice(5, messagesApi.length);
                                                                    }
                                                                    if (messagesApi != null && messagesApi.length > 0) {
                                                                        for (var n = 0; n < messagesApi.length; n++) {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                                                detail: messagesApi[n]
                                                                            }));
                                                                            document.dispatchEvent(new CustomEvent(TEMPLATE_MESSAGE, {
                                                                                detail: messagesApi[n]
                                                                            }));
                                                                            if (n == (messagesApi.length - 1)) {
                                                                                await sleep(mis * 2000);
                                                                                var d = new Date();
                                                                                var dformat = [d.getMonth() + 1,
                                                                                        d.getDate(),
                                                                                        d.getFullYear()
                                                                                    ].join('/') + ' ' +
                                                                                    [d.getHours(),
                                                                                        d.getMinutes(),
                                                                                        d.getSeconds()
                                                                                    ].join(':');
                                                                                document.getElementById("sendReport").style.display = "block";
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                                                document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                                                document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                                                                if (messagesApi[n].messageText == '') {
                                                                                    document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                                                }
                                                                                var divText = document.getElementById("sendReport").outerHTML;
                                                                                var myWindow = window.open();
                                                                                var doc = myWindow.document;
                                                                                doc.open();
                                                                                doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                                                doc.close();
                                                                                document.getElementById("sendReportBody").innerHTML = '';
                                                                                location.reload();
                                                                            }
                                                                        }
                                                                    }
                                                                    document.getElementById("whatsomessages").remove();
                                                                }
                                                            });
                                                        })
                                                    });
                                                })
                                            });
                                        })
                                    });
                                }
                            });
                        });
                    });
                } else {
                    alert('Please select file or message');
                }
            }
            if (ExcelLink != null && ExcelLink != "") {
                if (message != null && message != "" || Files.length > 0) {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    chrome.storage.local.set({
                        "reportMessage": messageText
                    });
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if (ExcelVal[n][selectionItem]) {
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            } else {
                                ExcelVal.splice(i, 1);
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }
                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                "templateImage": fileBase,
                                "template": template,
                                'messageText': result
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: async() => {
                                    debugger;
                                    chrome.storage.local.get("messagesApi", async({
                                        messagesApi
                                    }) => {
                                        chrome.storage.local.get("reportMessage", async({
                                            reportMessage
                                        }) => {
                                            chrome.storage.local.get("bt", async({
                                                bt
                                            }) => {
                                                chrome.storage.local.get("mis", async({
                                                    mis
                                                }) => {
                                                    chrome.storage.local.get("at", async({
                                                        at
                                                    }) => {
                                                        chrome.storage.local.get("mim", async({
                                                            mim
                                                        }) => {
                                                            chrome.storage.local.get("isDemo", async({
                                                                isDemo
                                                            }) => {
                                                                var totalSuccess = 0;
                                                                var totalFail = 0;
                                                                const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                                                const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                                                const TEMPLATE_MESSAGE = "GOT_TEMPLATE_MESSAGE";

                                                                document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                                                    try {
                                                                        var result = e.detail.result;
                                                                        var ValidNumber = e.detail.number;
                                                                        tBodyhtml = "";
                                                                        tBodyhtml += "<tr>";
                                                                        if (result.numberExists) {
                                                                            totalSuccess++;
                                                                            tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                                        } else {
                                                                            totalFail++;
                                                                            tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                                        }
                                                                        tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                                        if (result.numberExists) {
                                                                            tBodyhtml += "<td> Sent </td>";
                                                                            tBodyhtml += "<td></td>";
                                                                        } else {
                                                                            tBodyhtml += "<td> Fail </td>";
                                                                            tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                                        }
                                                                        tBodyhtml += `</tr>`;
                                                                        document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                                                    } catch (ex) {
                                                                        console.log(ex);
                                                                    }
                                                                });

                                                                if (messagesApi != null && messagesApi.length > 0) {
                                                                    let wam = document.getElementById("whatsomessages");
                                                                    if (!wam) {
                                                                        var whatso = document.createElement("div");
                                                                        whatso.id = "whatsomessages";
                                                                        document.body.append(whatso);
                                                                        whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                        var html = "";
                                                                        html += "Please do not perform any activity during the whatso automation extension";
                                                                        document.getElementById("whatsomessages").append(html);
                                                                    }
                                                                    if (messagesApi.length > 0 && isDemo) {
                                                                        messagesApi.splice(5, messagesApi.length);
                                                                    }
                                                                    if (messagesApi != null && messagesApi.length > 0) {
                                                                        for (var n = 0; n < messagesApi.length; n++) {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                                                detail: messagesApi[n]
                                                                            }));

                                                                            document.dispatchEvent(new CustomEvent(TEMPLATE_MESSAGE, {
                                                                                detail: messagesApi[n]
                                                                            }));
                                                                            if (n == (messagesApi.length - 1)) {
                                                                                await sleep(mis * 2000);
                                                                                var d = new Date();
                                                                                var dformat = [d.getMonth() + 1,
                                                                                        d.getDate(),
                                                                                        d.getFullYear()
                                                                                    ].join('/') + ' ' +
                                                                                    [d.getHours(),
                                                                                        d.getMinutes(),
                                                                                        d.getSeconds()
                                                                                    ].join(':');
                                                                                document.getElementById("sendReport").style.display = "block";
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                                                document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                                                document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                                                                if (messagesApi[n].messageText == '') {
                                                                                    document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                                                }
                                                                                var divText = document.getElementById("sendReport").outerHTML;
                                                                                var myWindow = window.open();
                                                                                var doc = myWindow.document;
                                                                                doc.open();
                                                                                doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                                                doc.close();
                                                                                document.getElementById("sendReportBody").innerHTML = '';
                                                                                location.reload();
                                                                            }

                                                                        }
                                                                    }
                                                                    document.getElementById("whatsomessages").remove();
                                                                }
                                                            });
                                                        })
                                                    });
                                                })
                                            });
                                        })
                                    });
                                }
                            });
                        });
                    });
                } else {
                    alert('Please select file or message');
                }
            } else if (commaSeprated != null && commaSeprated != "") {
                ExcelVal = commaSeprated.split(',');
                document.getElementById('countNumber').innerHTML = ExcelVal.length;
                var messageText = document.getElementById('message').value;
                chrome.storage.local.set({
                    "reportMessage": messageText
                });
                var spliceList = [];
                var objectMake = [];
                if (ExcelVal.length > 0) {
                    for (var n = 0; n < ExcelVal.length; n++) {
                        var numberMobile = ExcelVal[n].toString().replace(/[^0-9]/g, '');
                        if (numberMobile.length > 5 && numberMobile.length < 20) {
                            ExcelVal[n] = numberMobile.replace(/[^0-9]/g, '');
                        } else {
                            spliceList.push(n);
                        }
                    }
                    if (spliceList.length > 0) {
                        for (var x = 0; x < spliceList.length; x++) {
                            ExcelVal.splice(spliceList[x], 1);
                        }
                    }
                    for (var n = 0; n < ExcelVal.length; n++) {
                        var replacements = ExcelVal[n];
                        const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                            // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                            return replacements[key] !== undefined ?
                                "" + replacements[key] :
                                "";
                        });
                        objectMake.push({
                            'toNumber': ExcelVal[n],
                            "templateImage": fileBase,
                            "template": template,
                            'messageText': result
                        });
                    }
                    chrome.storage.local.set({
                        "messagesApi": objectMake
                    });
                }
                chrome.windows.getCurrent(w => {
                    chrome.tabs.query({
                        active: true,
                        windowId: w.id
                    }, tabs => {
                        const tabId = tabs[0].id;
                        chrome.scripting.executeScript({
                            target: {
                                tabId: tabId
                            },
                            function: async() => {
                                chrome.storage.local.get("messagesApi", async({
                                    messagesApi
                                }) => {
                                    chrome.storage.local.get("messagesFileApi", async({
                                        messagesFileApi
                                    }) => {
                                        chrome.storage.local.get("reportMessage", async({
                                            reportMessage
                                        }) => {
                                            chrome.storage.local.get("bt", async({
                                                bt
                                            }) => {
                                                chrome.storage.local.get("mis", async({
                                                    mis
                                                }) => {
                                                    chrome.storage.local.get("at", async({
                                                        at
                                                    }) => {
                                                        chrome.storage.local.get("mim", async({
                                                            mim
                                                        }) => {
                                                            chrome.storage.local.get("isDemo", async({
                                                                isDemo
                                                            }) => {
                                                                var totalSuccess = 0;
                                                                var totalFail = 0;
                                                                const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                                                const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                                                const TEMPLATE_MESSAGE = "GOT_TEMPLATE_MESSAGE";
                                                                document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                                                    try {
                                                                        var result = e.detail.result;
                                                                        var ValidNumber = e.detail.number;
                                                                        tBodyhtml = "";
                                                                        tBodyhtml += "<tr>";
                                                                        if (result.numberExists) {
                                                                            totalSuccess++;
                                                                            tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                                        } else {
                                                                            totalFail++;
                                                                            tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                                        }
                                                                        tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                                        if (result.numberExists) {
                                                                            tBodyhtml += "<td> Sent </td>";
                                                                            tBodyhtml += "<td></td>";
                                                                        } else {
                                                                            tBodyhtml += "<td> Fail </td>";
                                                                            tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                                        }
                                                                        tBodyhtml += `</tr>`;
                                                                        document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                                                    } catch (ex) {
                                                                        console.log(ex);
                                                                    }
                                                                });
                                                                if (messagesApi != null && messagesApi.length > 0) {
                                                                    debugger;
                                                                    let wam = document.getElementById("whatsomessages");
                                                                    if (!wam) {
                                                                        var whatso = document.createElement("div");
                                                                        whatso.id = "whatsomessages";
                                                                        document.body.append(whatso);
                                                                        whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                        var html = "";
                                                                        html += "Please do not perform any activity during the whatso automation extension";
                                                                        document.getElementById("whatsomessages").append(html);
                                                                    }
                                                                    if (messagesApi.length > 0 && isDemo) {
                                                                        messagesApi.splice(5, messagesApi.length);
                                                                    }
                                                                    if (messagesFileApi.length > 0 && isDemo) {
                                                                        messagesFileApi.splice(5, messagesFileApi.length);
                                                                    }
                                                                    if (messagesApi != null && messagesApi.length > 0) {
                                                                        for (var n = 0; n < messagesApi.length; n++) {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                                                detail: messagesApi[n]
                                                                            }))
                                                                            document.dispatchEvent(new CustomEvent(TEMPLATE_MESSAGE, {
                                                                                detail: messagesApi[n]
                                                                            }));
                                                                            if (n == (messagesApi.length - 1)) {
                                                                                await sleep(mis * 2000);
                                                                                var d = new Date();
                                                                                var dformat = [d.getMonth() + 1,
                                                                                        d.getDate(),
                                                                                        d.getFullYear()
                                                                                    ].join('/') + ' ' +
                                                                                    [d.getHours(),
                                                                                        d.getMinutes(),
                                                                                        d.getSeconds()
                                                                                    ].join(':');
                                                                                document.getElementById("sendReport").style.display = "block";
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                                                document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                                                document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                                                                if (messagesApi[n].messageText == '') {
                                                                                    document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                                                }
                                                                                var divText = document.getElementById("sendReport").outerHTML;
                                                                                var myWindow = window.open();
                                                                                var doc = myWindow.document;
                                                                                doc.open();
                                                                                doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                                                doc.close();
                                                                                document.getElementById("sendReportBody").innerHTML = '';
                                                                                location.reload();
                                                                            }
                                                                        }
                                                                    }
                                                                    document.getElementById("whatsomessages").remove();
                                                                }
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                })
                            }
                        });
                    });
                });
            } else {
                alert('Please select contacts excel');
            }
        } else if (attachment) {
            if (file != null && file != "") {
                if (message != null && message != "" || Files.length > 0) {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    chrome.storage.local.set({
                        "reportMessage": messageText
                    });
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if(ExcelVal[n][selectionItem]){
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            }else{
                                ExcelVal.splice(i, 1); 
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }
                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                'files' : [],
                                'messageText': result
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }
                    var objectMakeFiles = [];
                    if (Files.length > 0) {
                        for (var a = 0; a < Files.length; a++) {
                            objectMakeFiles.push({
                                'file': Files[a].file,
                                "fileName": Files[a].fileName,
                                "toNumber" : "",
                                'caption': Files[a].caption
                            });
                        }
                        chrome.storage.local.set({
                            "messagesFileApi": objectMakeFiles
                        });
                    }
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: sendAttachmentFiles
                            });
                        });
                    });
                } else {
                    alert('Please select file or message');
                }
            } else if (ExcelLink != null && ExcelLink != "") {
                if (message != null && message != "" || Files.length > 0) {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    chrome.storage.local.set({
                        "reportMessage": messageText
                    });
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if (ExcelVal[n][selectionItem]) {
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            } else {
                                ExcelVal.splice(i, 1);
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }
                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                'files': [],
                                'messageText': result
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }
                    var objectMakeFiles = [];
                    if (Files.length > 0) {
                            for (var a = 0; a < Files.length; a++) {
                                var Captionreplacements = ExcelVal[n];
                                const result = Files[a].caption.replace(/#([^#]+)#/g, (match, key) => {
                                    // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                    return Captionreplacements[key] !== undefined ?
                                        "" + Captionreplacements[key] :
                                        "";
                                });
                                objectMakeFiles.push({
                                    'file': Files[a].file,
                                    "fileName": Files[a].fileName,
                                    "toNumber" : "",
                                    'caption': result
                                });
                            }
                        chrome.storage.local.set({
                            "messagesFileApi": objectMakeFiles
                        });
                    }
                    
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: sendAttachmentFiles
                            });
                        });
                    });
                }
            } else if (commaSeprated != null && commaSeprated != "") {
                ExcelVal = commaSeprated.split(',');
                document.getElementById('countNumber').innerHTML = ExcelVal.length;
                var messageText = document.getElementById('message').value;
                chrome.storage.local.set({
                    "reportMessage": messageText
                });
                var spliceList = [];
                var objectMake = [];
                if (ExcelVal.length > 0) {
                    for (var n = 0; n < ExcelVal.length; n++) {
                        var numberMobile = ExcelVal[n].toString().replace(/[^0-9]/g, '');
                        if (numberMobile.length > 5 && numberMobile.length < 20) {
                            ExcelVal[n] = numberMobile.replace(/[^0-9]/g, '');
                        } else {
                            spliceList.push(n);
                        }
                    }
                    if (spliceList.length > 0) {
                        for (var x = 0; x < spliceList.length; x++) {
                            ExcelVal.splice(spliceList[x], 1);
                        }
                    }

                    for (var n = 0; n < ExcelVal.length; n++) {
                        var replacements = ExcelVal[n];
                        const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                            // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                            return replacements[key] !== undefined ?
                                "" + replacements[key] :
                                "";
                        });
                        objectMake.push({
                            'toNumber': ExcelVal[n],
                            'files': [],
                            'messageText': result
                        });
                    }
                    chrome.storage.local.set({
                        "messagesApi": objectMake
                    });
                }
                var objectMakeFiles = [];
                if (Files.length > 0) {
                        for (var a = 0; a < Files.length; a++) {
                            var Captionreplacements = ExcelVal[n];
                            const result = Files[a].caption.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return Captionreplacements[key] !== undefined ?
                                    "" + Captionreplacements[key] :
                                    "";
                            });
                            objectMakeFiles.push({
                                'file': Files[a].file,
                                "fileName": Files[a].fileName,
                                "toNumber" : "",
                                'caption': result
                            });
                        chrome.storage.local.set({
                            "messagesFileApi": objectMakeFiles
                        });
                    }
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: sendAttachmentFiles
                            });
                        });
                    });
                }
            } else {
                alert('Please select contacts excel');
            }
        } else if (listButton) {
            if (file != null && file != "") {
                if (message != null && message != "") {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if (ExcelVal[n][selectionItem]) {
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            } else {
                                ExcelVal.splice(i, 1);
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }
                        var ListItems = [];
                        for (var i = 0; i < $("#dynamicList").children().length; i++) {
                            var count = i + 1;
                            ListItems.push({
                                "rowId": count.toString(),
                                "title": $("#List" + count).val()
                            });
                        }
                        var sections = [{
                            title: document.getElementById("SectionTitle").value,
                            rows: ListItems,
                        }]
                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                'buttonText': document.getElementById("ButtonTitle").value,
                                'description': result,
                                "sections": sections
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: async() => {
                                    debugger;
                                    chrome.storage.local.get("messagesApi", async({
                                        messagesApi
                                    }) => {
                                        chrome.storage.local.get("bt", async({
                                            bt
                                        }) => {
                                            chrome.storage.local.get("mis", async({
                                                mis
                                            }) => {
                                                chrome.storage.local.get("at", async({
                                                    at
                                                }) => {
                                                    chrome.storage.local.get("mim", async({
                                                        mim
                                                    }) => {
                                                        chrome.storage.local.get("isDemo", async({
                                                            isDemo
                                                        }) => {
                                                            const LIST_MESSAGE = "GOT_LIST_MESSAGE";
                                                            if (messagesApi != null && messagesApi.length > 0) {
                                                                let wam = document.getElementById("whatsomessages");
                                                                if (!wam) {
                                                                    var whatso = document.createElement("div");
                                                                    whatso.id = "whatsomessages";
                                                                    document.body.append(whatso);
                                                                    whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                    var html = "";
                                                                    html += "Please do not perform any activity during the whatso automation extension";
                                                                    document.getElementById("whatsomessages").append(html);
                                                                }
                                                                if (messagesApi.length > 0 && isDemo) {
                                                                    messagesApi.splice(5, messagesApi.length);
                                                                }
                                                                if (messagesApi != null && messagesApi.length > 0) {
                                                                    for (var n = 0; n < messagesApi.length; n++) {
                                                                        if (messagesApi[n].messageText != '') {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            document.dispatchEvent(new CustomEvent(LIST_MESSAGE, {
                                                                                detail: messagesApi[n]
                                                                            }));
                                                                        }
                                                                    }
                                                                }
                                                                document.getElementById("whatsomessages").remove();
                                                            }
                                                        });
                                                    })
                                                })
                                            })
                                        })
                                    })
                                }
                            });
                        });
                    });
                } else {
                    alert('Please select file or message');
                }
            } else if (commaSeprated != null && commaSeprated != "") {
                ExcelVal = commaSeprated.split(',');
                document.getElementById('countNumber').innerHTML = ExcelVal.length;
                var messageText = document.getElementById('message').value;
                var spliceList = [];
                var objectMake = [];
                if (ExcelVal.length > 0) {
                    for (var n = 0; n < ExcelVal.length; n++) {
                        var numberMobile = ExcelVal[n].toString().replace(/[^0-9]/g, '');
                        if (numberMobile.length > 5 && numberMobile.length < 20) {
                            ExcelVal[n] = numberMobile.replace(/[^0-9]/g, '');
                        } else {
                            spliceList.push(n);
                        }
                    }
                    if (spliceList.length > 0) {
                        for (var x = 0; x < spliceList.length; x++) {
                            ExcelVal.splice(spliceList[x], 1);
                        }
                    }

                    var ListItems = [];
                    for (var i = 0; i < $("#dynamicList").children().length; i++) {
                        var count = i + 1;
                        ListItems.push({
                            "rowId": count.toString(),
                            "title": $("#List" + count).val()
                        });
                    }
                    var sections = [{
                        title: document.getElementById("SectionTitle").value,
                        rows: ListItems,
                    }]
                    for (var n = 0; n < ExcelVal.length; n++) {
                        var replacements = ExcelVal[n];
                        const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                            // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                            return replacements[key] !== undefined ?
                                "" + replacements[key] :
                                "";
                        });
                        objectMake.push({
                            'toNumber': ExcelVal[n],
                            'buttonText': document.getElementById("ButtonTitle").value,
                            'description': messageText,
                            "sections": sections
                        });
                    }
                    chrome.storage.local.set({
                        "messagesApi": objectMake
                    });
                }
                chrome.windows.getCurrent(w => {
                    chrome.tabs.query({
                        active: true,
                        windowId: w.id
                    }, tabs => {
                        const tabId = tabs[0].id;
                        chrome.scripting.executeScript({
                            target: {
                                tabId: tabId
                            },
                            function: async() => {
                                chrome.storage.local.get("messagesApi", async({
                                    messagesApi
                                }) => {
                                    chrome.storage.local.get("messagesFileApi", async({
                                        messagesFileApi
                                    }) => {
                                        chrome.storage.local.get("bt", async({
                                            bt
                                        }) => {
                                            chrome.storage.local.get("mis", async({
                                                mis
                                            }) => {
                                                chrome.storage.local.get("at", async({
                                                    at
                                                }) => {
                                                    chrome.storage.local.get("mim", async({
                                                        mim
                                                    }) => {
                                                        chrome.storage.local.get("isDemo", async({
                                                            isDemo
                                                        }) => {
                                                            const LIST_MESSAGE = "GOT_LIST_MESSAGE";
                                                            if (messagesApi != null && messagesApi.length > 0) {
                                                                debugger;
                                                                let wam = document.getElementById("whatsomessages");
                                                                if (!wam) {
                                                                    var whatso = document.createElement("div");
                                                                    whatso.id = "whatsomessages";
                                                                    document.body.append(whatso);
                                                                    whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                    var html = "";
                                                                    html += "Please do not perform any activity during the whatso automation extension";
                                                                    document.getElementById("whatsomessages").append(html);
                                                                }
                                                                if (messagesApi.length > 0 && isDemo) {
                                                                    messagesApi.splice(5, messagesApi.length);
                                                                }
                                                                if (messagesFileApi.length > 0 && isDemo) {
                                                                    messagesFileApi.splice(5, messagesFileApi.length);
                                                                }
                                                                if (messagesApi != null && messagesApi.length > 0) {
                                                                    for (var n = 0; n < messagesApi.length; n++) {
                                                                        if (messagesApi[n].messageText != '') {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            document.dispatchEvent(new CustomEvent(LIST_MESSAGE, {
                                                                                detail: messagesApi[n]
                                                                            }));
                                                                        }
                                                                    }
                                                                }
                                                                document.getElementById("whatsomessages").remove();
                                                            }
                                                        });
                                                    });
                                                });

                                            });
                                        });

                                    });
                                })
                            }
                        });
                    });
                });
            } else {
                alert('Please select contacts excel');
            }
        } else {
            if (file != null && file != "") {
                if (message != null && message != "" || Files.length > 0) {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    chrome.storage.local.set({
                        "reportMessage": messageText
                    });
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if (ExcelVal[n][selectionItem]) {
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            } else {
                                ExcelVal.splice(i, 1);
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }

                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                'messageText': result
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }

                    if (typeAutomation == 1) {
                        chrome.windows.getCurrent(w => {
                            chrome.tabs.query({
                                active: true,
                                windowId: w.id
                            }, tabs => {
                                const tabId = tabs[0].id;
                                chrome.scripting.executeScript({
                                    target: {
                                        tabId: tabId
                                    },
                                    function: async() => {
                                        debugger;
                                        chrome.storage.local.get("messagesApi", async({
                                            messagesApi
                                        }) => {
                                            chrome.storage.local.get("reportMessage", async({
                                                reportMessage
                                            }) => {
                                                chrome.storage.local.get("isDemo", async({
                                                    isDemo
                                                }) => {
                                                    chrome.storage.local.get("bt", async({
                                                        bt
                                                    }) => {
                                                        chrome.storage.local.get("mis", async({
                                                            mis
                                                        }) => {
                                                            chrome.storage.local.get("at", async({
                                                                at
                                                            }) => {
                                                                chrome.storage.local.get("mim", async({
                                                                    mim
                                                                }) => {
                                                                    const EVENT_NAME = "GOT_WWAPI";
                                                                    var totalSuccess = 0;
                                                                    var totalFail = 0;
                                                                    const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                                                    const MESSAGE_EVENT_NAME = "GOT_WWAPI_SEND_MESSAGE";
                                                                    const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                                                    document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                                                        try {
                                                                            var result = e.detail.result;
                                                                            var ValidNumber = e.detail.number;
                                                                            tBodyhtml = "";
                                                                            tBodyhtml += "<tr>";
                                                                            if (result.numberExists) {
                                                                                totalSuccess++;
                                                                                tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                                            } else {
                                                                                totalFail++;
                                                                                tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                                            }
                                                                            tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                                            if (result.numberExists) {
                                                                                tBodyhtml += "<td> Sent </td>";
                                                                                tBodyhtml += "<td></td>";
                                                                            } else {
                                                                                tBodyhtml += "<td> Fail </td>";
                                                                                tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                                            }
                                                                            tBodyhtml += `</tr>`;
                                                                            document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                                                        } catch (ex) {
                                                                            console.log(ex);
                                                                        }
                                                                    });
                                                                    if (messagesApi != null && messagesApi.length > 0) {
                                                                        let wam = document.getElementById("whatsomessages");
                                                                        if (!wam) {
                                                                            var whatso = document.createElement("div");
                                                                            whatso.id = "whatsomessages";
                                                                            document.body.append(whatso);
                                                                            whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                            var html = "";
                                                                            html += "Please do not perform any activity during the whatso automation extension";
                                                                            document.getElementById("whatsomessages").append(html);
                                                                        }
                                                                        if (messagesApi.length > 0 && isDemo) {
                                                                            messagesApi.splice(5, messagesApi.length);
                                                                        }
                                                                        for (var n = 0; n < messagesApi.length; n++) {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            if (messagesApi != null && messagesApi.length > 0) {
                                                                                document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                                                    detail: messagesApi[n]
                                                                                }));
                                                                                if (messagesApi[n].messageText != '') {
                                                                                    document.dispatchEvent(new CustomEvent(MESSAGE_EVENT_NAME, {
                                                                                        detail: messagesApi[n]
                                                                                    }));
                                                                                }
                                                                            }
                                                                            if (n == (messagesApi.length - 1)) {
                                                                                await sleep(mis * 2000);
                                                                                var d = new Date();
                                                                                var dformat = [d.getMonth() + 1,
                                                                                        d.getDate(),
                                                                                        d.getFullYear()
                                                                                    ].join('/') + ' ' +
                                                                                    [d.getHours(),
                                                                                        d.getMinutes(),
                                                                                        d.getSeconds()
                                                                                    ].join(':');
                                                                                document.getElementById("sendReport").style.display = "block";
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                                                document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                                                document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                                                                if (messagesApi[n].messageText == '') {
                                                                                    document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                                                }
                                                                                var divText = document.getElementById("sendReport").outerHTML;
                                                                                var myWindow = window.open();
                                                                                var doc = myWindow.document;
                                                                                doc.open();
                                                                                doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                                                doc.close();
                                                                                document.getElementById("sendReportBody").innerHTML = '';
                                                                                location.reload();
                                                                            }
                                                                        }
                                                                        document.getElementById("whatsomessages").remove();
                                                                    }
                                                                });
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    }
                                });
                            });
                        });
                    } else {
                        chrome.windows.getCurrent(w => {
                            chrome.tabs.query({
                                active: true,
                                windowId: w.id
                            }, tabs => {
                                const tabId = tabs[0].id;
                                chrome.scripting.executeScript({
                                    target: {
                                        tabId: tabId
                                    },
                                    function: textType,
                                });
                            });
                        });
                    }
                } else {
                    alert('Please select file or message');
                }
            } else if (ExcelLink != null && ExcelLink != "") {
                if (message != null && message != "" || Files.length > 0) {
                    document.getElementById('countNumber').innerHTML = ExcelVal.length;
                    var messageText = document.getElementById('message').value;
                    chrome.storage.local.set({
                        "reportMessage": messageText
                    });
                    var selectionItem = document.getElementById('selection-val').value;
                    var objectMake = [];
                    var spliceList = [];
                    if (ExcelVal.length > 0) {
                        for (var n = 0; n < ExcelVal.length; n++) {
                            if (ExcelVal[n][selectionItem]) {
                                var numberMobile = ExcelVal[n][selectionItem].toString().replace(/[^0-9]/g, '');
                                if (numberMobile.length > 5 && numberMobile.length < 20) {
                                    ExcelVal[n][selectionItem] = numberMobile.replace(/[^0-9]/g, '');
                                } else {
                                    spliceList.push(n);
                                }
                            } else {
                                ExcelVal.splice(i, 1);
                            }
                        }
                        if (spliceList.length > 0) {
                            for (var x = 0; x < spliceList.length; x++) {
                                ExcelVal.splice(spliceList[x], 1);
                            }
                        }

                        for (var n = 0; n < ExcelVal.length; n++) {
                            var replacements = ExcelVal[n];
                            const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                                // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                                return replacements[key] !== undefined ?
                                    "" + replacements[key] :
                                    "";
                            });
                            objectMake.push({
                                'toNumber': ExcelVal[n][selectionItem],
                                'messageText': result
                            });
                        }
                        chrome.storage.local.set({
                            "messagesApi": objectMake
                        });
                    }
                    if (typeAutomation == 1) {
                        chrome.windows.getCurrent(w => {
                            chrome.tabs.query({
                                active: true,
                                windowId: w.id
                            }, tabs => {
                                const tabId = tabs[0].id;
                                chrome.scripting.executeScript({
                                    target: {
                                        tabId: tabId
                                    },
                                    function: async() => {
                                        debugger;
                                        chrome.storage.local.get("messagesApi", async({
                                            messagesApi
                                        }) => {
                                            chrome.storage.local.get("reportMessage", async({
                                                reportMessage
                                            }) => {
                                                chrome.storage.local.get("isDemo", async({
                                                    isDemo
                                                }) => {
                                                    chrome.storage.local.get("bt", async({
                                                        bt
                                                    }) => {
                                                        chrome.storage.local.get("mis", async({
                                                            mis
                                                        }) => {
                                                            chrome.storage.local.get("at", async({
                                                                at
                                                            }) => {
                                                                chrome.storage.local.get("mim", async({
                                                                    mim
                                                                }) => {
                                                                    var totalSuccess = 0;
                                                                    var totalFail = 0;
                                                                    const EVENT_NAME = "GOT_WWAPI";
                                                                    const MESSAGE_EVENT_NAME = "GOT_WWAPI_SEND_MESSAGE";
                                                                    const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                                                    const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                                                    document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                                                        try {
                                                                            var result = e.detail.result;
                                                                            var ValidNumber = e.detail.number;
                                                                            tBodyhtml = "";
                                                                            tBodyhtml += "<tr>";
                                                                            if (result.numberExists) {
                                                                                totalSuccess++;
                                                                                tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                                            } else {
                                                                                totalFail++;
                                                                                tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                                            }
                                                                            tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                                            // if(result.canReceiveMessage){
                                                                            //     tBodyhtml += "<td> SENT </td>";
                                                                            // }else{
                                                                            //     tBodyhtml += "<td> FAIL </td>";
                                                                            // }
                                                                            if (result.numberExists) {
                                                                                tBodyhtml += "<td> Sent </td>";
                                                                                tBodyhtml += "<td></td>";
                                                                            } else {
                                                                                tBodyhtml += "<td> Fail </td>";
                                                                                tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                                            }
                                                                            tBodyhtml += `</tr>`;
                                                                            document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                                                        } catch (ex) {
                                                                            console.log(ex);
                                                                        }
                                                                    });
                                                                    if (messagesApi != null && messagesApi.length > 0) {
                                                                        let wam = document.getElementById("whatsomessages");
                                                                        if (!wam) {
                                                                            var whatso = document.createElement("div");
                                                                            whatso.id = "whatsomessages";
                                                                            document.body.append(whatso);
                                                                            whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                            var html = "";
                                                                            html += "Please do not perform any activity during the whatso automation extension";
                                                                            document.getElementById("whatsomessages").append(html);
                                                                        }
                                                                        if (messagesApi.length > 0 && isDemo) {
                                                                            messagesApi.splice(5, messagesApi.length);
                                                                        }
                                                                        for (var n = 0; n < messagesApi.length; n++) {
                                                                            const sleep = m => new Promise(r => setTimeout(r, m));
                                                                            if (n != 0) {
                                                                                if (mis > 0) {
                                                                                    await sleep(mis * 1000);
                                                                                }
                                                                                if (at && mim && (n % at) == 0) {
                                                                                    await sleep(mim * 60000);
                                                                                }
                                                                            }
                                                                            if (messagesApi != null && messagesApi.length > 0) {
                                                                                document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                                                    detail: messagesApi[n]
                                                                                }));
                                                                                if (messagesApi[n].messageText != '') {
                                                                                    document.dispatchEvent(new CustomEvent(MESSAGE_EVENT_NAME, {
                                                                                        detail: messagesApi[n]
                                                                                    }));
                                                                                }
                                                                            }
                                                                            if (n == (messagesApi.length - 1)) {
                                                                                await sleep(mis * 2000);
                                                                                var d = new Date();
                                                                                var dformat = [d.getMonth() + 1,
                                                                                        d.getDate(),
                                                                                        d.getFullYear()
                                                                                    ].join('/') + ' ' +
                                                                                    [d.getHours(),
                                                                                        d.getMinutes(),
                                                                                        d.getSeconds()
                                                                                    ].join(':');
                                                                                document.getElementById("sendReport").style.display = "block";
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                                                document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                                                document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                                                document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                                                                if (messagesApi[n].messageText == '') {
                                                                                    document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                                                }
                                                                                var divText = document.getElementById("sendReport").outerHTML;
                                                                                var myWindow = window.open();
                                                                                var doc = myWindow.document;
                                                                                doc.open();
                                                                                doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                                                doc.close();
                                                                                document.getElementById("sendReportBody").innerHTML = '';
                                                                                location.reload();
                                                                            }

                                                                        }

                                                                        document.getElementById("whatsomessages").remove();
                                                                    }
                                                                });
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    }
                                });
                            });
                        });
                    } else {
                        chrome.windows.getCurrent(w => {
                            chrome.tabs.query({
                                active: true,
                                windowId: w.id
                            }, tabs => {
                                const tabId = tabs[0].id;
                                chrome.scripting.executeScript({
                                    target: {
                                        tabId: tabId
                                    },
                                    function: textType,
                                });
                            });
                        });
                    }
                }
            } else if (commaSeprated != null && commaSeprated != "") {
                ExcelVal = commaSeprated.split(',');
                document.getElementById('countNumber').innerHTML = ExcelVal.length;
                var messageText = document.getElementById('message').value;
                chrome.storage.local.set({
                    "reportMessage": messageText
                });
                var spliceList = [];
                var objectMake = [];
                if (ExcelVal.length > 0) {
                    for (var n = 0; n < ExcelVal.length; n++) {
                        var numberMobile = ExcelVal[n].toString().replace(/[^0-9]/g, '');
                        if (numberMobile.length > 5 && numberMobile.length < 20) {
                            ExcelVal[n] = numberMobile.replace(/[^0-9]/g, '');
                        } else {
                            spliceList.push(n);
                        }
                    }
                    if (spliceList.length > 0) {
                        for (var x = 0; x < spliceList.length; x++) {
                            ExcelVal.splice(spliceList[x], 1);
                        }
                    }

                    for (var n = 0; n < ExcelVal.length; n++) {
                        var replacements = ExcelVal[n];
                        const result = messageText.replace(/#([^#]+)#/g, (match, key) => {
                            // If there's a replacement for the key, return that replacement with a `<br />`. Otherwise, return a empty string.
                            return replacements[key] !== undefined ?
                                "" + replacements[key] :
                                "";
                        });
                        objectMake.push({
                            'toNumber': ExcelVal[n],
                            'messageText': result
                        });
                    }
                    chrome.storage.local.set({
                        "messagesApi": objectMake
                    });
                }
                if (typeAutomation == 1) {
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: async() => {
                                    chrome.storage.local.get("messagesApi", async({
                                        messagesApi
                                    }) => {
                                        chrome.storage.local.get("reportMessage", async({
                                            reportMessage
                                        }) => {
                                            chrome.storage.local.get("isDemo", async({
                                                isDemo
                                            }) => {
                                                chrome.storage.local.get("bt", async({
                                                    bt
                                                }) => {
                                                    chrome.storage.local.get("mis", async({
                                                        mis
                                                    }) => {
                                                        chrome.storage.local.get("at", async({
                                                            at
                                                        }) => {
                                                            chrome.storage.local.get("mim", async({
                                                                mim
                                                            }) => {
                                                                var totalSuccess = 0;
                                                                var totalFail = 0;
                                                                const EVENT_NAME = "GOT_WWAPI";
                                                                const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                                                const MESSAGE_EVENT_NAME = "GOT_WWAPI_SEND_MESSAGE";
                                                                const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                                                document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                                                    try {
                                                                        var result = e.detail.result;
                                                                        var ValidNumber = e.detail.number;
                                                                        tBodyhtml = "";
                                                                        tBodyhtml += "<tr>";
                                                                        if (result.numberExists) {
                                                                            totalSuccess++;
                                                                            tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                                        } else {
                                                                            totalFail++;
                                                                            tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                                        }
                                                                        tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                                        if (result.numberExists) {
                                                                            tBodyhtml += "<td> Sent </td>";
                                                                            tBodyhtml += "<td></td>";
                                                                        } else {
                                                                            tBodyhtml += "<td> Fail </td>";
                                                                            tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                                        }
                                                                        tBodyhtml += `</tr>`;
                                                                        document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                                                    } catch (ex) {
                                                                        console.log(ex);
                                                                    }
                                                                });
                                                                if (messagesApi != null && messagesApi.length > 0) {
                                                                    debugger;
                                                                    let wam = document.getElementById("whatsomessages");
                                                                    if (!wam) {
                                                                        var whatso = document.createElement("div");
                                                                        whatso.id = "whatsomessages";
                                                                        document.body.append(whatso);
                                                                        whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                                        var html = "";
                                                                        html += "Please do not perform any activity during the whatso automation extension";
                                                                        document.getElementById("whatsomessages").append(html);
                                                                    }
                                                                    if (messagesApi.length > 0 && isDemo) {
                                                                        messagesApi.splice(5, messagesApi.length);
                                                                    }
                                                                    for (var n = 0; n < messagesApi.length; n++) {
                                                                        const sleep = m => new Promise(r => setTimeout(r, m));
                                                                        if (n != 0) {
                                                                            if (mis > 0) {
                                                                                await sleep(mis * 1000);
                                                                            }
                                                                            if (at && mim && (n % at) == 0) {
                                                                                await sleep(mim * 60000);
                                                                            }
                                                                        }

                                                                        document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                                            detail: messagesApi[n]
                                                                        }));

                                                                        if (messagesApi != null && messagesApi.length > 0) {
                                                                            if (messagesApi[n].messageText != '') {
                                                                                document.dispatchEvent(new CustomEvent(MESSAGE_EVENT_NAME, {
                                                                                    detail: messagesApi[n]
                                                                                }));
                                                                            }
                                                                        }

                                                                        if (n == (messagesApi.length - 1)) {
                                                                            await sleep(mis * 2000);
                                                                            var d = new Date();
                                                                            var dformat = [d.getMonth() + 1,
                                                                                    d.getDate(),
                                                                                    d.getFullYear()
                                                                                ].join('/') + ' ' +
                                                                                [d.getHours(),
                                                                                    d.getMinutes(),
                                                                                    d.getSeconds()
                                                                                ].join(':');
                                                                            document.getElementById("sendReport").style.display = "block";
                                                                            document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                                            document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                                            document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                                            document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                                            document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                                            document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                                                            if (messagesApi[n].messageText == '') {
                                                                                document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                                            }
                                                                            var divText = document.getElementById("sendReport").outerHTML;
                                                                            var myWindow = window.open();
                                                                            var doc = myWindow.document;
                                                                            doc.open();
                                                                            doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                                            doc.close();
                                                                            document.getElementById("sendReportBody").innerHTML = '';
                                                                            location.reload();
                                                                        }
                                                                    }

                                                                    document.getElementById("whatsomessages").remove();
                                                                }
                                                            });
                                                        });
                                                    });
                                                });
                                            });
                                        });
                                    });
                                }
                            });
                        });
                    });
                } else {
                    chrome.windows.getCurrent(w => {
                        chrome.tabs.query({
                            active: true,
                            windowId: w.id
                        }, tabs => {
                            const tabId = tabs[0].id;
                            chrome.scripting.executeScript({
                                target: {
                                    tabId: tabId
                                },
                                function: textType,
                            });
                        });
                    });
                }
            } else {
                alert('Please select contacts excel');
            }
        }
    }
    
    async function sendAttachmentFiles(){
        chrome.storage.local.get("messagesApi", async({
            messagesApi
        }) => {
            chrome.storage.local.get("reportMessage", async({
                reportMessage
            }) => {
                chrome.storage.local.get("messagesFileApi", async({
                    messagesFileApi
                }) => {
                    chrome.storage.local.get("bt", async({
                        bt
                    }) => {
                        chrome.storage.local.get("mis", async({
                            mis
                        }) => {
                            chrome.storage.local.get("at", async({
                                at
                            }) => {
                                chrome.storage.local.get("mim", async({
                                    mim
                                }) => {
                                    chrome.storage.local.get("isDemo", async({
                                        isDemo
                                    }) => {
                                        var totalSuccess = 0;
                                        var totalFail = 0;
                                        var attachmentsList = '';
                                        const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                        const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                        const EVENT_NAME = "GOT_WWAPI";
                                        const MESSAGE_EVENT_NAME = "GOT_WWAPI_SEND_MESSAGE";
                                        document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                            try {
                                                var result = e.detail.result;
                                                var ValidNumber = e.detail.number;
                                                tBodyhtml = "";
                                                tBodyhtml += "<tr>";
                                                if (result.numberExists) {
                                                    totalSuccess++;
                                                    tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                                } else {
                                                    totalFail++;
                                                    tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                                }
                                                tBodyhtml += "<td>" + ValidNumber + "</td>";
                                                // if(result.canReceiveMessage){
                                                //     tBodyhtml += "<td> SENT </td>";
                                                // }else{
                                                //     tBodyhtml += "<td> FAIL </td>";
                                                // }
                                                if (result.numberExists) {
                                                    tBodyhtml += "<td> Sent </td>";
                                                    tBodyhtml += "<td></td>";
                                                } else {
                                                    tBodyhtml += "<td> Fail </td>";
                                                    tBodyhtml += "<td>This number is not using whatsapp</td>";
                                                }
                                                // if(result.isBusiness){
                                                //     tBodyhtml += "<td> YES </td>";
                                                // }else{
                                                //     tBodyhtml += "<td> No </td>";
                                                // }
                                                tBodyhtml += `</tr>`;
                                                document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                            } catch (ex) {
                                                console.log(ex);
                                            }
                                        });
                                        if (messagesApi != null && messagesApi.length > 0) {
                                            let wam = document.getElementById("whatsomessages");
                                            if (!wam) {
                                                var whatso = document.createElement("div");
                                                whatso.id = "whatsomessages";
                                                document.body.append(whatso);
                                                whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                                var html = "";
                                                html += "Please do not perform any activity during the whatso automation extension";
                                                document.getElementById("whatsomessages").append(html);
                                            }
                                            if (messagesApi.length > 0 && isDemo) {
                                                messagesApi.splice(5, messagesApi.length);
                                            }
                                            if (messagesFileApi.length > 0 && isDemo) {
                                                messagesFileApi.splice(5, messagesFileApi.length);
                                            }
                                            debugger;
                                            var object = [];
                                            var ind = 0;
                                            for (var n = 0; n < messagesApi.length; n++) {
                                                const sleep = m => new Promise(r => setTimeout(r, m));
                                                if (n != 0) {
                                                    if (mis > 0) {
                                                        await sleep(mis * 1000);
                                                    }
                                                    if (at && mim && (n % at) == 0) {
                                                        await sleep(mim * 60000);
                                                    }
                                                }
                                                if (messagesApi != null && messagesApi.length > 0) {
                                                    document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                                        detail: messagesApi[n]
                                                    }));

                                                    if (messagesApi[n].messageText != '') {
                                                        document.dispatchEvent(new CustomEvent(MESSAGE_EVENT_NAME, {
                                                            detail: messagesApi[n]
                                                        }));
                                                    }
                                                }
                                                if (messagesFileApi != null && messagesFileApi.length > 0) {
                                                    for (var g = 0; g < messagesFileApi.length; g++) {
                                                        await sleep(3000);
                                                        if (n == 0) {
                                                            attachmentsList += '<div>';
                                                            attachmentsList += `<svg xmlns="http://www.w3.org/2000/svg" fill="#000000" viewBox="0 0 100 100" width="40px" height="40px">    <path d="M 34.179688 10.164062 C 32.103687 10.164062 30.615234 11.426266 30.615234 13.697266 L 30.648438 25.806641 C 30.648438 28.846641 32.770234 30.712891 35.615234 30.712891 C 38.460234 30.712891 40.615234 29.002891 40.615234 25.962891 L 40.615234 14.306641 L 39.613281 14.306641 L 39.523438 25.869141 C 39.523438 28.079141 37.599438 29.808594 35.648438 29.808594 C 33.697437 29.808594 31.615234 28.049844 31.615234 25.839844 L 31.644531 13.611328 C 31.644531 12.304328 33.077484 11.126953 34.271484 11.126953 C 35.465484 11.126953 36.615234 12.275031 36.615234 13.582031 L 36.615234 24.056641 C 36.615234 24.056641 36.139813 25.056641 35.632812 25.056641 C 35.125812 25.056641 34.486234 24.700391 34.615234 24.150391 L 34.615234 14.308594 L 33.615234 14.308594 L 33.582031 23.964844 C 33.582031 25.344844 34.32225 25.964844 35.65625 25.964844 C 36.99025 25.964844 37.615234 25.249141 37.615234 23.869141 L 37.615234 13.664062 C 37.615234 11.393062 36.255687 10.164062 34.179688 10.164062 z M 41.613281 11.306641 C 41.061281 11.306641 40.613281 11.754641 40.613281 12.306641 C 40.613281 12.858641 41.061281 13.306641 41.613281 13.306641 L 59.613281 13.306641 L 59.613281 23.792969 C 59.613281 29.039969 63.881906 33.306641 69.128906 33.306641 L 79.613281 33.306641 L 79.613281 82.574219 C 79.613281 86.837219 76.146812 90.306641 71.882812 90.306641 L 28.347656 90.306641 C 24.084656 90.306641 20.615234 86.838219 20.615234 82.574219 L 20.615234 21.039062 C 20.615234 16.776063 24.083656 13.308594 28.347656 13.308594 L 29.615234 13.308594 C 30.167234 13.308594 30.615234 12.860594 30.615234 12.308594 C 30.615234 11.756594 30.167234 11.308594 29.615234 11.308594 L 28.347656 11.308594 C 22.981656 11.308594 18.615234 15.672062 18.615234 21.039062 L 18.615234 82.574219 C 18.615234 87.940219 22.980656 92.306641 28.347656 92.306641 L 71.882812 92.306641 C 77.248812 92.306641 81.613281 87.940219 81.613281 82.574219 L 81.613281 32.554688 C 81.613281 32.289688 81.508313 32.035656 81.320312 31.847656 L 61.072266 11.599609 C 60.885266 11.411609 60.630234 11.306641 60.365234 11.306641 L 41.613281 11.306641 z M 60.613281 13.966797 L 78.951172 32.306641 L 69.128906 32.306641 C 64.433906 32.306641 60.613281 28.487969 60.613281 23.792969 L 60.613281 13.966797 z M 28.371094 19.505859 C 28.245219 19.481734 28.110094 19.505984 27.996094 19.583984 C 25.878094 21.023984 24.613281 23.406078 24.613281 25.955078 L 24.613281 78.617188 C 24.613281 82.856187 28.048484 86.306641 32.271484 86.306641 L 67.955078 86.306641 C 72.178078 86.306641 75.613234 82.856188 75.615234 78.617188 L 75.615234 60.806641 C 75.615234 60.530641 75.391234 60.306641 75.115234 60.306641 C 74.839234 60.306641 74.615234 60.530641 74.615234 60.806641 L 74.615234 78.617188 C 74.615234 82.305187 71.628031 85.306641 67.957031 85.306641 L 32.273438 85.306641 C 28.602438 85.306641 25.615234 82.305188 25.615234 78.617188 L 25.615234 25.955078 C 25.615234 23.737078 26.714594 21.664156 28.558594 20.410156 C 28.786594 20.255156 28.846406 19.945797 28.691406 19.716797 C 28.613906 19.603297 28.496969 19.529984 28.371094 19.505859 z M 75.113281 47.306641 C 74.837281 47.306641 74.613281 47.530641 74.613281 47.806641 L 74.613281 50.806641 C 74.613281 51.082641 74.837281 51.306641 75.113281 51.306641 C 75.390281 51.306641 75.613281 51.082641 75.613281 50.806641 L 75.613281 47.806641 C 75.613281 47.530641 75.389281 47.306641 75.113281 47.306641 z M 30.113281 51.306641 C 29.837281 51.306641 29.613281 51.530641 29.613281 51.806641 C 29.613281 52.082641 29.837281 52.306641 30.113281 52.306641 L 53.113281 52.306641 C 53.390281 52.306641 53.613281 52.082641 53.613281 51.806641 C 53.613281 51.530641 53.389281 51.306641 53.113281 51.306641 L 30.113281 51.306641 z M 75.113281 52.306641 C 74.837281 52.306641 74.613281 52.530641 74.613281 52.806641 L 74.613281 58.806641 C 74.613281 59.082641 74.837281 59.306641 75.113281 59.306641 C 75.390281 59.306641 75.613281 59.082641 75.613281 58.806641 L 75.613281 52.806641 C 75.613281 52.530641 75.389281 52.306641 75.113281 52.306641 z M 30.113281 58.306641 C 29.837281 58.306641 29.613281 58.530641 29.613281 58.806641 C 29.613281 59.082641 29.837281 59.306641 30.113281 59.306641 L 44.113281 59.306641 C 44.390281 59.306641 44.613281 59.082641 44.613281 58.806641 C 44.613281 58.530641 44.389281 58.306641 44.113281 58.306641 L 30.113281 58.306641 z M 46.113281 58.306641 C 45.837281 58.306641 45.613281 58.530641 45.613281 58.806641 C 45.613281 59.082641 45.837281 59.306641 46.113281 59.306641 L 70.113281 59.306641 C 70.390281 59.306641 70.613281 59.082641 70.613281 58.806641 C 70.613281 58.530641 70.389281 58.306641 70.113281 58.306641 L 46.113281 58.306641 z M 30.113281 65.306641 C 29.837281 65.306641 29.613281 65.530641 29.613281 65.806641 C 29.613281 66.082641 29.837281 66.306641 30.113281 66.306641 L 48.113281 66.306641 C 48.390281 66.306641 48.613281 66.082641 48.613281 65.806641 C 48.613281 65.530641 48.389281 65.306641 48.113281 65.306641 L 30.113281 65.306641 z M 50.113281 65.306641 C 49.837281 65.306641 49.613281 65.530641 49.613281 65.806641 C 49.613281 66.082641 49.837281 66.306641 50.113281 66.306641 L 61.113281 66.306641 C 61.390281 66.306641 61.613281 66.082641 61.613281 65.806641 C 61.613281 65.530641 61.389281 65.306641 61.113281 65.306641 L 50.113281 65.306641 z M 63.113281 65.306641 C 62.837281 65.306641 62.613281 65.530641 62.613281 65.806641 C 62.613281 66.082641 62.837281 66.306641 63.113281 66.306641 L 71.113281 66.306641 C 71.390281 66.306641 71.613281 66.082641 71.613281 65.806641 C 71.613281 65.530641 71.389281 65.306641 71.113281 65.306641 L 63.113281 65.306641 z M 30.113281 72.306641 C 29.837281 72.306641 29.613281 72.530641 29.613281 72.806641 C 29.613281 73.082641 29.837281 73.306641 30.113281 73.306641 L 54.113281 73.306641 C 54.390281 73.306641 54.613281 73.082641 54.613281 72.806641 C 54.613281 72.530641 54.389281 72.306641 54.113281 72.306641 L 30.113281 72.306641 z M 57.113281 72.306641 C 56.837281 72.306641 56.613281 72.530641 56.613281 72.806641 C 56.613281 73.082641 56.837281 73.306641 57.113281 73.306641 L 70.113281 73.306641 C 70.390281 73.306641 70.613281 73.082641 70.613281 72.806641 C 70.613281 72.530641 70.389281 72.306641 70.113281 72.306641 L 57.113281 72.306641 z"/></svg>`;
                                                            attachmentsList += '<div>'+ messagesFileApi[g].fileName+'</div>';
                                                            attachmentsList += '<div>Caption : '+ messagesFileApi[g].caption+'</div>';
                                                            if(g != (messagesApi[n].files.length -1)){
                                                                attachmentsList += '<hr style="margin:5px 0"/>';
                                                            }
                                                            attachmentsList += '</div>';
                                                        }
                                                        messagesFileApi[g].toNumber = messagesApi[n].toNumber;
                                                        messagesApi[n].files = messagesFileApi[g];
                                                        document.dispatchEvent(new CustomEvent(EVENT_NAME, {
                                                            detail: messagesApi[n].files
                                                        }));
                                                    }
                                                }
                                                if (n == (messagesApi.length - 1)) {
                                                    await sleep(mis * 2000);
                                                    var d = new Date();
                                                    var dformat = [d.getMonth() + 1,
                                                            d.getDate(),
                                                            d.getFullYear()
                                                        ].join('/') + ' ' +
                                                        [d.getHours(),
                                                            d.getMinutes(),
                                                            d.getSeconds()
                                                        ].join(':');
                                                    document.getElementById("sendReport").style.display = "block";
                                                    document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                                    document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                                    document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                                    document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                                    document.getElementById("overviewMessage").children[0].children[1].children[1].children[0].innerHTML = attachmentsList;
                                                    document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                                    if (messagesApi[n].messageText == '') {
                                                        document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                                    }
                                                    var divText = document.getElementById("sendReport").outerHTML;
                                                    var myWindow = window.open();
                                                    var doc = myWindow.document;
                                                    doc.open();
                                                    doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                                    doc.close();
                                                    document.getElementById("sendReportBody").innerHTML = '';
                                                    debugger;
                                                    setTimeout(function(){
                                                        location.reload();
                                                    },15000);
                                                }

                                            }

                                            document.getElementById("whatsomessages").remove();
                                            // var Inreds = setInterval(function() {
                                            //     var bufferIcon = document.querySelector('span[data-icon="status-time"]');
                                            //     if (!bufferIcon) {
                                            //         clearInterval(Inreds);
                                            //         location.reload();
                                            //     }
                                            // }, 5000);
                                        }
                                    });
                                });
                            });
                        });
                    });
                });
        });
    });
    }
    // async function textType() {
    //     debugger;
    //     chrome.storage.local.get("messagesApi", async({
    //         messagesApi
    //     }) => {
    //         chrome.storage.local.get("reportMessage", async({
    //             reportMessage
    //         }) => {
    //             chrome.storage.local.get("isDemo", async({
    //                 isDemo
    //             }) => {
    //                 chrome.storage.local.get("bt", async({
    //                     bt
    //                 }) => {
    //                     chrome.storage.local.get("mis", async({
    //                         mis
    //                     }) => {
    //                         chrome.storage.local.get("at", async({
    //                             at
    //                         }) => {
    //                             chrome.storage.local.get("mim", async({
    //                                 mim
    //                             }) => {
    //                                 var totalSuccess = 0;
    //                                 var totalFail = 0;
    //                                 var texti = 0;
    //                                 var speed = 50;
    //                                 var numberCount = 0;
    //                                 var isWaiting = false;
    //                                 const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
    //                                 const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
    //                                 document.getElementById("sendReportBody").innerHTML = '';
    //                                 async function awaiting(second) {
    //                                     const sleep = m => new Promise(r => setTimeout(r, m));
    //                                     isWaiting = true;
    //                                     await sleep(mim * second * 1000);
    //                                     isWaiting = false;
    //                                     return;
    //                                 }
    //                                 async function messageList(n) {
    //                                     if (n != 0) {
    //                                         if (mis > 0) {
    //                                             await awaiting(mis * 1)
    //                                         }
    //                                         if (at && mim && (n % at) == 0) {
    //                                             await awaiting(mim * 60)
    //                                         }
    //                                     }
    //                                     await awaiting(1)
    //                                     document.getElementsByClassName("_3z9_h")[0].innerHTML = "<a href='' id='sender' class='executor'>.</a>";
    //                                     await awaiting(1)
    //                                     if (messagesApi[n].toNumber) {
    //                                         document.getElementById("sender").setAttribute("href", "https://web.whatsapp.com/send?phone=" + parseInt(messagesApi[n].toNumber));
    //                                         await awaiting(1)
    //                                         document.getElementById("sender").click();
    //                                         await awaiting(4)
    //                                     } else {
    //                                         if (document.getElementsByClassName('_20C5O')[0]) {
    //                                             texti = messagesApi[n].messageText.length;
    //                                             document.getElementsByClassName('_20C5O')[0].click();
    //                                         }
    //                                         texti = 0;
    //                                         typingComplete = true;
    //                                         numberCount++;
    //                                         if (numberCount < messagesApi.length) {
    //                                             messageList(numberCount);
    //                                         }
    //                                     }
    //                                     var element = document.querySelectorAll('[title="Type a message"]')[0];
    //                                     if (element) {
    //                                         element.addEventListener('input', function() {
    //                                             element.textContent += messagesApi[n].messageText.charAt(texti);
    //                                             texti++;
    //                                             setTimeout(typeWriter, speed);
    //                                         });
    //                                         if (messagesApi != null && messagesApi.length > 0) {
    //                                             if (messagesApi[n].messageText != '') {
    //                                                 await typeWriter();
    //                                             }
    //                                         }
    //                                     } else {
    //                                         if (document.getElementsByClassName('_20C5O')[0]) {
    //                                             texti = messagesApi[n].messageText.length;
    //                                             document.getElementsByClassName('_20C5O')[0].click();
    //                                         }
    //                                         texti = 0;
    //                                         typingComplete = true;
    //                                         numberCount++;
    //                                         if (numberCount < messagesApi.length) {
    //                                             messageList(numberCount);
    //                                         }
    //                                     }
    //                                     document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
    //                                         detail: messagesApi[n]
    //                                     }));
    //                                 }
    //                                 async function typeWriter() {
    //                                     if (!isWaiting) {
    //                                         if (texti < messagesApi[numberCount].messageText.length) {
    //                                             var event = new Event('input', {
    //                                                 'bubbles': true,
    //                                                 'cancelable': true
    //                                             });
    //                                             if (document.getElementsByClassName('_20C5O')[0]) {
    //                                                 texti = messagesApi[numberCount].messageText.length;
    //                                                 document.getElementsByClassName('_20C5O')[0].click();
    //                                             } else if (document.querySelectorAll('[title="Type a message"]')[0]) {
    //                                                 let keydown = new KeyboardEvent('keydown', {key: 'a', code: 'KeyA', keyCode: 65});
    //                                                 document.querySelectorAll('[title="Type a message"]')[0].dispatchEvent(keydown);
    //                                             }
    //                                             typingComplete = false;
    //                                         }
    //                                         if (texti == messagesApi[numberCount].messageText.length) {
    //                                             if (document.querySelectorAll('[data-icon="send"]')[0]) {
    //                                                 document.querySelectorAll('[data-icon="send"]')[0].click();
    //                                             } else if (document.getElementsByClassName('_20C5O')[0]) {
    //                                                 document.getElementsByClassName('_20C5O')[0].click();
    //                                             }
    //                                             texti = 0;
    //                                             typingComplete = true;
    //                                             numberCount++;
    //                                             if (numberCount < messagesApi.length) {
    //                                                 messageList(numberCount);
    //                                             } else {
    //                                                 await awaiting(1);
    //                                             }
    //                                             if (numberCount == messagesApi.length && typingComplete) {
    //                                                 await awaiting(2);
    //                                                 numberCount = 0;
    //                                                 var d = new Date();
    //                                                 var dformat = [d.getMonth() + 1,
    //                                                         d.getDate(),
    //                                                         d.getFullYear()
    //                                                     ].join('/') + ' ' +
    //                                                     [d.getHours(),
    //                                                         d.getMinutes(),
    //                                                         d.getSeconds()
    //                                                     ].join(':');
    //                                                 document.getElementById("sendReport").style.display = "block";
    //                                                 document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
    //                                                 document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
    //                                                 document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
    //                                                 document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
    //                                                 document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
    //                                                 document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
    //                                                 if (messagesApi[numberCount].messageText == '') {
    //                                                     document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
    //                                                 }
    //                                                 var divText = document.getElementById("sendReport").outerHTML;
    //                                                 var myWindow = window.open();
    //                                                 var doc = myWindow.document;
    //                                                 doc.open();
    //                                                 doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
    //                                                 doc.close();
    //                                                 document.getElementById("sendReportBody").innerHTML = '';
    //                                                 location.reload();
    //                                             }
    //                                             return;
    //                                         }
    //                                     }
    //                                 }
    //                                 document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
    //                                     try {
    //                                         var result = e.detail.result;
    //                                         var ValidNumber = e.detail.number;
    //                                         tBodyhtml = "";
    //                                         tBodyhtml += "<tr>";
    //                                         if (result.numberExists) {
    //                                             totalSuccess++;
    //                                             tBodyhtml += "<td class='IconSuccessEncoded'></td>";
    //                                         } else {
    //                                             totalFail++;
    //                                             tBodyhtml += "<td class='IconErrorEncoded'></td>";
    //                                         }
    //                                         tBodyhtml += "<td>" + ValidNumber + "</td>";
    //                                         if (result.numberExists) {
    //                                             tBodyhtml += "<td> Sent </td>";
    //                                             tBodyhtml += "<td></td>";
    //                                         } else {
    //                                             tBodyhtml += "<td> Fail </td>";
    //                                             tBodyhtml += "<td>This number is not using whatsapp</td>";
    //                                         }
    //                                         tBodyhtml += `</tr>`;
    //                                         document.getElementById("sendReportBody").innerHTML += tBodyhtml;
    //                                     } catch (ex) {
    //                                         console.log(ex);
    //                                     }
    //                                 });
    //                                 if (messagesApi != null && messagesApi.length > 0) {
    //                                     if (messagesApi.length > 0 && isDemo) {
    //                                         messagesApi.splice(5, messagesApi.length);
    //                                     }
    //                                     messageList(numberCount);

    //                                 }
    //                             });
    //                         });
    //                     });
    //                 });
    //             });
    //         });
    //     });
    // }
    async function textType() {
        debugger;
        chrome.storage.local.get("messagesApi", async({
            messagesApi
        }) => {
            chrome.storage.local.get("reportMessage", async({
                reportMessage
            }) => {
                chrome.storage.local.get("isDemo", async({
                    isDemo
                }) => {
                    chrome.storage.local.get("bt", async({
                        bt
                    }) => {
                        chrome.storage.local.get("mis", async({
                            mis
                        }) => {
                            chrome.storage.local.get("at", async({
                                at
                            }) => {
                                chrome.storage.local.get("mim", async({
                                    mim
                                }) => {
                                    var totalSuccess = 0;
                                    var totalFail = 0;
                                    var numberCount = 0;
                                    const CHECK_NUMBER_STATUS = "GOT_CHECK_NUMBER_STATUS";
                                    const VALID_CHECK_NUMBER_STATUS = "GOT_VALID_CHECK_NUMBER_STATUS";
                                    document.getElementById("sendReportBody").innerHTML = '';
                                    if (messagesApi != null && messagesApi.length > 0) {
                                        if (messagesApi.length > 0 && isDemo) {
                                            messagesApi.splice(5, messagesApi.length);
                                        }
                                    }
                                    let wam = document.getElementById("whatsomessages");
                                    if (!wam) {
                                        var whatso = document.createElement("div");
                                        whatso.id = "whatsomessages";
                                        document.body.append(whatso);
                                        whatso.setAttribute("style", 'text-align:center;line-height:40px;max-width:600px;margin:0 auto;padding:15px;position:fixed;height: 200px;top:200px;right:200px;left:200px;bottom:200px;z-index:999;background:#fff;display: flex;align-items: center;justify-content: center;border: 5px solid #1EA185;font-size: 36px;');
                                        var html = "";
                                        html += "Please do not perform any activity during the whatso automation extension";
                                        document.getElementById("whatsomessages").append(html);
                                    }
                                    document.addEventListener(VALID_CHECK_NUMBER_STATUS, async function(e) {
                                        try {
                                            var result = e.detail.result;
                                            var ValidNumber = e.detail.number;
                                            tBodyhtml = "";
                                            tBodyhtml += "<tr>";
                                            if (result.numberExists) {
                                                totalSuccess++;
                                                tBodyhtml += "<td class='IconSuccessEncoded'></td>";
                                            } else {
                                                totalFail++;
                                                tBodyhtml += "<td class='IconErrorEncoded'></td>";
                                            }
                                            tBodyhtml += "<td>" + ValidNumber + "</td>";
                                            if (result.numberExists) {
                                                tBodyhtml += "<td> Sent </td>";
                                                tBodyhtml += "<td></td>";
                                            } else {
                                                tBodyhtml += "<td> Fail </td>";
                                                tBodyhtml += "<td>This number is not using whatsapp</td>";
                                            }
                                            tBodyhtml += `</tr>`;
                                            document.getElementById("sendReportBody").innerHTML += tBodyhtml;
                                        } catch (ex) {
                                            console.log(ex);
                                        }
                                    });
                                    async function awaiting(second) {
                                        const sleep = m => new Promise(r => setTimeout(r, m));
                                        isWaiting = true;
                                        await sleep(mim * second * 1000);
                                        isWaiting = false;
                                        return;
                                    }
                                    var executor = document.createElement("a");
                                    executor.id = "sender";
                                    executor.className = "executor";
                                    executor.innerHTML = '.';
                                    document.body.append(executor);
                                    for (var n = 0; n < messagesApi.length; n++) {
                                        if (n != 0) {
                                            if (mis > 0) {
                                                await awaiting(mis * 1)
                                            }
                                            if (at && mim && (n % at) == 0) {
                                                await awaiting(mim * 60)
                                            }
                                        }
                                        document.dispatchEvent(new CustomEvent(CHECK_NUMBER_STATUS, {
                                            detail: messagesApi[n]
                                        }));
                                        await awaiting(1)
                                        document.getElementById("sender").setAttribute("href", "https://web.whatsapp.com/send?phone=" + parseInt(messagesApi[n].toNumber) + "&text=" + encodeURIComponent(messagesApi[n].messageText));
                                        await awaiting(1)
                                        document.getElementById("sender").click();
                                        await awaiting(4)
                                        if (document.querySelectorAll('[data-icon="send"]')[0]) {
                                            document.querySelectorAll('[data-icon="send"]')[0].click();
                                        } else if (document.getElementsByClassName('_20C5O')[0]) {
                                            document.getElementsByClassName('_20C5O')[0].click();
                                        }
                                        if (n == (messagesApi.length - 1)) {
                                            await awaiting(2);
                                            numberCount = 0;
                                            var d = new Date();
                                            var dformat = [d.getMonth() + 1,
                                                    d.getDate(),
                                                    d.getFullYear()
                                                ].join('/') + ' ' +
                                                [d.getHours(),
                                                    d.getMinutes(),
                                                    d.getSeconds()
                                                ].join(':');
                                            document.getElementById("sendReport").style.display = "block";
                                            document.getElementById("overview").children[0].children[0].children[1].children[0].innerHTML = dformat;
                                            document.getElementById("overview").children[0].children[0].children[1].children[1].innerHTML = messagesApi.length;
                                            document.getElementById("overview").children[0].children[0].children[1].children[2].innerHTML = totalSuccess;
                                            document.getElementById("overview").children[0].children[0].children[1].children[3].innerHTML = totalFail;
                                            document.getElementById("overviewMessage").children[0].children[0].children[1].children[0].children[0].innerHTML = reportMessage;
                                            document.getElementById("overviewMessage").children[0].children[1].style.display = "none";
                                            if (messagesApi[numberCount].messageText == '') {
                                                document.getElementById("overviewMessage").children[0].children[0].style.display = "none";
                                            }
                                            var divText = document.getElementById("sendReport").outerHTML;
                                            var myWindow = window.open();
                                            var doc = myWindow.document;
                                            doc.open();
                                            doc.write(`<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">` + divText);
                                            doc.close();
                                            document.getElementById("sendReportBody").innerHTML = '';
                                            location.reload();
                                        }
                                    }
                                    document.getElementById("whatsomessages").remove();
                                });
                            });
                        });
                    });
                });
            });
        });
    }
    async function checkUseHere() {
        if (document.getElementsByClassName("_2Zdgs").length > 0) {
            document.getElementsByClassName("_2Zdgs")[0].click();
            return true;
        }
    }
    async function showAlert() {
        if (document.getElementsByClassName("_2Zdgs")[0]) {
            document.getElementsByClassName("_2Zdgs")[0].click();
        } else {
            if (document.getElementsByClassName("_4sWnG").length > 0) {
                document.getElementsByClassName("_4sWnG")[0].click();
            }
        }
        return true;
    }

    function submitLogin(event) {
        document.getElementById("sendMessageBox").classList.remove("hide")
        document.getElementById("LoginBox").classList.add("hide")
    }
} catch {
    isPause = false;
}