// const IMAGE_NOT_SENT = "GOT_IMAGE_NOT_SENT";
try {
    var isFirstTime = true;
    window.onload = async function() {
        if(window.location.origin == "https://web.whatsapp.com"){
            const sleep = m => new Promise(r => setTimeout(r, m));
            capturePhone();
            addScriptToPage(chrome.runtime.getURL("WhatsoWAPI.js"));
            await sleep(500);
            createReportTable();
        }
    };

    function createReportTable(){
        if(window.location.origin == "https://web.whatsapp.com"){
            var report = document.createElement("div");
            report.id = "sendReport";
            report.style.display = "none";
            document.body.append(report);
            var html = "";
            html += `
            <!DOCTYPE html>
            <html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-16LE">
                <meta content="en-us" http-equiv="Content-Language">
                <title>
                    Sent Report
                </title>
                <style>
                    /* Body style, for the entire document */
                    body {
                        background: #F3F3F4;
                        color: #1E1E1F;
                        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
                        padding: 0;
                        margin: 0;
                    }
                    /* Header1 style, used for the main title */
                    #sendReport h1 {
                        padding: 10px 0px 10px 10px;
                        font-size: 21pt;
                        background-color: #E2E2E2;
                        border-bottom: 1px #C1C1C2 solid;
                        color: #201F20;
                        margin: 0;
                        font-weight: normal;
                    }
                    /* Header2 style, used for "Overview" and other sections */
                    #sendReport h2 {
                        font-size: 18pt;
                        font-weight: normal;
                        padding: 15px 0 5px 0;
                        margin: 0;
                    }
                    /* Header3 style, used for sub-sections, such as project name */
                    #sendReport h3 {
                        font-weight: normal;
                        font-size: 15pt;
                        margin: 0;
                        padding: 15px 0 5px 0;
                        background-color: transparent;
                    }
                    /* Color all hyperlinks one color */
                    #sendReport a {
                        color: #1382CE;
                    }
                    /* Table styles */
                    #sendReport table {
                        border-spacing: 0 0;
                        border-collapse: collapse;
                        font-size: 10pt;
                    }
            
                    #sendReport table th {
                            background: #E7E7E8;
                            text-align: left;
                            text-decoration: none;
                            font-weight: normal;
                            padding: 3px 6px 3px 6px;
                        }
            
                        #sendReport table td {
                            vertical-align: top;
                            padding: 3px 6px 5px 5px;
                            margin: 0px;
                            border: 1px solid #E7E7E8;
                            background: #F7F7F8;
                        }
                        #sendReport img.attachment{
                            border: 1px solid #e1e1e1;
                            margin: 0 10px;
                            height: 50px;
                        }
                    /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
                    #sendReport .localLink {
                        color: #1E1E1F;
                        background: #EEEEED;
                        text-decoration: none;
                    }
            
                    #sendReport .localLink:hover {
                            color: #1382CE;
                            background: #FFFF99;
                            text-decoration: none;
                        }
                    /* Center text, used in the over views cells that contain message level counts */
                    #sendReport .textCentered {
                        text-align: center;
                    }
                    /* The message cells in message tables should take up all avaliable space */
                    #sendReport .messageCell {
                        width: 100%;
                    }
                    /* Padding around the content after the h1 */
                    #sendReport #content {
                        padding: 0px 12px 12px 12px;
                    }
                    /* The overview table expands to width, with a max width of 97% */
                    #sendReport #overview table {
                        width: auto;
                        max-width: 75%;
                    }
                    /* The messages tables are always 97% width */
                    #sendReport #messages table {
                        width: 97%;
                    }
                    /* All Icons */
                    #sendReport .IconSuccessEncoded,#sendReport  .IconInfoEncoded,#sendReport  .IconWarningEncoded,#sendReport  .IconErrorEncoded {
                        min-width: 18px;
                        min-height: 18px;
                        background-repeat: no-repeat;
                        background-position: center;
                    }
                    /* Success icon encoded */
                    #sendReport .IconSuccessEncoded {
                        /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
                        /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
                        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABcElEQVR4Xq2TsUsCURzHv15g8ZJcBWlyiYYgCIWcb9DFRRwMW5TA2c0/QEFwFkxxUQdxVlBwCYWOi6IhWgQhBLHJUCkhLr/BW8S7gvrAg+N+v8/v+x68Z8MGy+XSCyABQAXgBgHGALoASkIIDWSLeLBetdHryMjd5IxQPWT4rn1c/P7+xxp72Cs9m5SZ0Bq2vPnbPFafK2zDvmNHypdC0BPkLlQhxJsCAhQoZwdZU5mwxh720qGo8MzTxTTKZDPCx2HoVzp6lz0Q9tKhyx0kGs8Ny+TkWRKk8lCROwEduhyg9l/6lunOPSfmH3NUH6uQ0KHLAe7JYvJjevm+DAMGJHToKtigE+vwvIidxLamb8IBY9e+C5LiXREkfho3TSd06HJA13/oh6T51MTsfQbHrsMynQ5dDihFjiK8JJAU9AKIWTp76dCVN7HWHrajmUEGvyF9nkbAE6gLIS7kTUyuf2gscLoJrElZo/Mvj+nPz/kLTmfnEwP3tB0AAAAASUVORK5CYII=);
                    }
                    /* Information icon encoded */
                    #sendReport .IconInfoEncoded {
                        /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
                        /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
                        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
                    }
                    /* Warning icon encoded */
                    #sendReport .IconWarningEncoded {
                        /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
                        /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
                        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
                    }
                    /* Error icon encoded */
                    #sendReport .IconErrorEncoded {
                        /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
                        /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
                        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
                    }
            
                    #sendReport .auto-style1 {
                        color: #1382CE;
                    }
            
                    #sendReport .auto-style2 {
                        text-align: left;
                    }
                </style>
                <script type="text/javascript" language="javascript">
            
                     // Startup
                     // Hook up the the loaded event for the document/window, to linkify the document content
                     var startupFunction = function() { linkifyElement("messages"); };
            
                     if(window.attachEvent)
                     {
                       window.attachEvent('onload', startupFunction);
                     }
                     else if (window.addEventListener)
                     {
                       window.addEventListener('load', startupFunction, false);
                     }
                     else
                     {
                       document.addEventListener('load', startupFunction, false);
                     }
            
                     // Toggles the visibility of table rows with the specified name
                     function toggleTableRowsByName(name)
                     {
                        var allRows = document.getElementsByTagName('tr');
                        for (i=0; i < allRows.length; i++)
                        {
                           var currentName = allRows[i].getAttribute('name');
                           if(!!currentName && currentName.indexOf(name) == 0)
                           {
                               var isVisible = allRows[i].style.display == '';
                               isVisible ? allRows[i].style.display = 'none' : allRows[i].style.display = '';
                           }
                        }
                     }
            
                     function scrollToFirstVisibleRow(name)
                     {
                        var allRows = document.getElementsByTagName('tr');
                        for (i=0; i < allRows.length; i++)
                        {
                           var currentName = allRows[i].getAttribute('name');
                           var isVisible = allRows[i].style.display == '';
                           if(!!currentName && currentName.indexOf(name) == 0 && isVisible)
                           {
                              allRows[i].scrollIntoView(true);
                              return true;
                           }
                        }
            
                        return false;
                     }
            
                     // Linkifies the specified text content, replaces candidate links with html links
                     function linkify(text)
                     {
                          if(!text || 0 === text.length)
                          {
                              return text;
                          }
            
                          // Find http, https and ftp links and replace them with hyper links
                          var urlLink = /(http|https|ftp)\:\/\/[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?\/?([a-zA-Z0-9\-\._\?\,\/\\\+&%\$#\=~;\{\}])*/gi;
            
                          return text.replace(urlLink, '<a href="$&">$&</a>') ;
                     }
            
                     // Linkifies the specified element by ID
                     function linkifyElement(id)
                     {
                         var element = document.getElementById(id);
                         if(!!element)
                         {
                           element.innerHTML = linkify(element.innerHTML);
                         }
                     }
            
                     function ToggleMessageVisibility(projectName)
                     {
                       if(!projectName || 0 === projectName.length)
                       {
                         return;
                       }
            
                       toggleTableRowsByName("MessageRowClass" + projectName);
                       toggleTableRowsByName('MessageRowHeaderShow' + projectName);
                       toggleTableRowsByName('MessageRowHeaderHide' + projectName);
                     }
            
                     function ScrollToFirstVisibleMessage(projectName)
                     {
                       if(!projectName || 0 === projectName.length)
                       {
                         return;
                       }
            
                       // First try the 'Show messages' row
                       if(!scrollToFirstVisibleRow('MessageRowHeaderShow' + projectName))
                       {
                         // Failed to find a visible row for 'Show messages', try an actual message row
                         scrollToFirstVisibleRow('MessageRowClass' + projectName);
                       }
                     }
                </script>
            </head>
            <body id="reportBody">
                <h1>
                    Sending Report
                </h1>
                <div id="content">
            
                    <h2>Sent details</h2>
                    <div id="overview">
                        <table style="width: 672px">
                            <tbody>
                                <tr>
                                    <th  style="width: 164px">Date </th>
                                    <th  style="width: 89px">
                                        Total
                                        Numbers
                                    </th>
                                    <th  style="width: 71px">Successful </th>
                                    <th  style="width: 63px">Failed</th>
                                </tr>
                                <tr>
                                    <td style="width: 164px">30 June 2022 09:38</td>
                                    <td style="width: 89px">4</td>
                                    <td style="width: 71px">4</td>
                                    <td style="width: 63px">0</td>
                                </tr>
                            </tbody>
                        </table>
            
                        <h2>Messages &amp; Attachments</h2>
                        <div id="overviewMessage">
                            <table style="width: 677px">
                                <thead>
                                    <tr>
                                        <th  style="width: 207px">Messages</th>
                                    </tr>
                                    <tr><td style='width: 207px'><span _locid='OverviewSolutionSpan'>This is a test message sent at : 30-06-2022 09:36:24</span></td></tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <th  style="width: 207px">Attachments</th>
                                    </tr>
                                    <tr>
                                        <td  style="width: 207px"></td>
                                    </tr>
                                </tbody>
            
                            </table>
            
            
                            <h2>Overview</h2>
                            <div id="overviewTable">
                                <table style="width: 677px">
                                    <thead>
                                        <tr>
                                            <th style="width: 15px"></th>
                                            <th  style="width: 207px">Number</th>
                                            <th  style="width: 63px">Status</th>
                                            <th  style="width: 246px">Reason</th>
                                        </tr>
                                    </thead>
                                    <tbody id="sendReportBody">
                                    </tbody>
                                </table>
                            </div>
            
                        </div>
                    </div>
            
            </body>
            </html>`;
            document.getElementById("sendReport").innerHTML = html;
        }
    }
    function capturePhone() {
        try {
            var data;
            if (window.localStorage.getItem("last-wid")) {
                data = window.localStorage.getItem("last-wid");
                myNumber = data.split("@")[0].substring(1);
            } else {
                data = window.localStorage.getItem("last-wid-md");
                myNumber = data.split(":")[0].substring(1);
            }
            chrome.storage.local.set({
                'fromNumber': myNumber
            });
            console.log(myNumber);
        } catch (e) {
            console.log(e);
        }
    }

    function querySelectorIncludesText(selector, text) {
        return Array.from(document.querySelectorAll(selector))
            .find(el => el.textContent.includes(text));
    }

    function addScriptToPage(e) {
        try {
            const t = document.createElement("script");
            t.type = "text/javascript";
            t.src = e;
            (document.head || document.body || document.documentElement).appendChild(t);
        } catch (e) {}
    }

    // var setLogo = setInterval(function() {
    //     var val = document.getElementsByClassName("_3GlyB")[0];
    //     var _2BYrr = document.getElementsByClassName("_2BYrr")[0];
    //     var _2Zdgs = querySelectorIncludesText("._2Zdgs", "Retry Now");
    //     if (_2Zdgs) {
    //         _2Zdgs.click();
    //     }
    //     if (val != undefined) {
    //         if (isFirstTime) {
    //             document.getElementsByClassName("_3DJrq")[0].innerHTML = "<a href='#' id='sender' class='executor'>.</a>";
    //             isFirstTime = false;
    //         }
    //         document.getElementsByClassName("_3GlyB")[0].innerHTML = '<img src="https://whatsocdn.s3.us-west-2.amazonaws.com/images/whatso-latest-logo.png" height="40" />';
    //     }

    //     if (_2BYrr != undefined) {
    //         document.getElementsByClassName("_2BYrr")[0].setAttribute("style", "margin-left: 115px;");
    //     }
    // }, 100)

} catch {

}