// eslint-disable-next-line no-unused-vars
/* global chrome */
/* exported closeTab */

if(typeof browser === "undefined" && typeof chrome !== "undefined") {
    var browser = chrome;
}

function checkOpenerClickMaster(protect) {
           
    try {
        window.opener.href;
    }
    catch(e){
      
        if (window.opener && protect===1)
        {
            window.opener=null;
            browser.runtime.sendMessage({action: "opener", "tab":"opener"});
        }
    }
}

// 3 - When opening a new tab, either through a link or JavaScript code, disable the opener object by default.
// preventing the target to get access to its openers.
browser.runtime.sendMessage({action:"checkOpener"});
  
function clickedClickMaster(e) {

    let target = e.target;
    if(target.getAttribute && target.getAttribute("data-click-master-unknown") !== null)
    {       
        e.preventDefault();
        e.stopImmediatePropagation();        
        browser.runtime.sendMessage({action: "userActionPremium", url: target.getAttribute("data-click-master-unknown") });
    }
    else {
        while (!target.href && target.parentNode) {
            target = target.parentNode;
        }
        try {
                    
            //1 - When an element does not display any href, only allow local URL targets and redirections. 
            if (!target.href || target.hostname==undefined) {              
                browser.runtime.sendMessage({action:"click", "href": "","protocol": window.location.protocol});
            }
            else
            {   
                let hrefProtocol = undefined;
    
                try {
                    
                    hrefProtocol = new URL(target.href).protocol;
       
                } finally {              
                    //1 - When a domain is instead displayed, only allow access to that domain.
                    //2 - If the user clicks an HTTPS link, only allow secure connections if there no additional interaction.
                    browser.runtime.sendMessage({action:"click", "href": target.hostname, "protocol": hrefProtocol || window.location.protocol, "text": target.innerText, "url": target.href  });
                }
                                      
            }
            
        } catch (e) {
            console.log(e);
        }
    }     
}

var observeDOM = (function(){
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
        eventListenerSupported = window.addEventListener;
    return function(obj, callback){
        if( MutationObserver ){
            // eslint-disable-next-line no-unused-vars
            var obs = new MutationObserver(function(mutations, _observer){
                if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
                    callback();
            });
            obs.observe( obj, { childList:true, subtree:true, attributes: true,
                characterData: true,  attributeOldValue: true});
        }
        else if( eventListenerSupported ){
            obj.addEventListener("DOMNodeInserted", callback, false);
            obj.addEventListener("DOMNodeRemoved", callback, false);
        }
    };
})();

observeDOM(window.document,function(){
    window.addEventListener("click", clickedClickMaster, true);
    window.addEventListener("mousedown", clickedClickMaster, true);   
});

(()=>{

    function isClickContextAnIframe () {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }
    
    function createMessagesPlaceholder() {
    
        if(document.querySelectorAll("#nrg-clicks-extension-note").length === 0)
        {
            const el = document.createElement("div");
            el.setAttribute("id", "nrg-clicks-extension-note");
            el.style.display = "none";
            el.innerHTML =
            `<div class="nrg-inner-container">
            <img id="close" alt="X" src="${browser.extension.getURL("images/cross_32.png")}"  />
              <img style="width: 24px;height: 24px;margin-top: 8.5px;float:left;margin-left: 15px;" alt="NRG" src="${browser.extension.getURL("images/icon48-allblack.png")}"  />
              <span data-from="" data-to="" data-linktext="" data-reason="" id="nrg-message"></span>
              <div class="nrg-dropdown">
              <input type="button" value="Options" style="padding: 5px!important; width: 80px!important;font-weight: normal!important;" />
                  <div class="nrg-dropdown-content">
                    <ul>
                        <li style="margin-left: 0px!important;" id="allow-once"></li>
                        <li style="margin-left: 0px!important;" id="allow"></li>
                        <li style="margin-left: 0px!important;" id="disable">Disable clicks protection on this Website</li>
                        <li style="margin-left: 0px!important;" id="alternative"></li>
                    </ul>
                    <div class="desc"></div>
                  </div>
              </div>
            </div>`;
    
            const waitForDocument = setInterval(()=>{
                try {
    
                    document.body.appendChild(el);
    
                    document.querySelector("#nrg-clicks-extension-note #allow-once").addEventListener("click", function() {
                        handleOptionsClick(document.querySelector("#nrg-clicks-extension-note #nrg-message"), "allow-once");
                    });
    
                    document.querySelector("#nrg-clicks-extension-note #allow").addEventListener("click", function() {
                        handleOptionsClick(document.querySelector("#nrg-clicks-extension-note #nrg-message"), "allow");
                    });
    
                    document.querySelector("#nrg-clicks-extension-note #disable").addEventListener("click", function() {
                        handleOptionsClick(document.querySelector("#nrg-clicks-extension-note #nrg-message"), "trust");
                    });
    
                    document.querySelector("#nrg-clicks-extension-note #alternative").addEventListener("click", function() {
                        handleOptionsClickPremium(document.querySelector("#nrg-clicks-extension-note #nrg-message"), "alternative");
                    });

                    document.querySelector("#nrg-clicks-extension-note #close").addEventListener("click", function() {
                        document.querySelector("#nrg-clicks-extension-note").style.display = "none";
                    });
    
                    browser.runtime.sendMessage({action: "domloaded"});
    
                    clearInterval(waitForDocument);
                // eslint-disable-next-line no-empty
                } catch {
                   
                }
            }, 500);
    
        }
    
    }
    
    function handleOptionsClick(target, userAction) {
    
        const tabUrl = window.location.href;
        const fromDomain = target.getAttribute("data-from");
        const toDomain = target.getAttribute("data-to");
        const linkTextDomain = target.getAttribute("data-linktext");
        const reason = target.getAttribute("data-reason");
        const url = target.getAttribute("data-url");
    
        browser.runtime.sendMessage({"action": "userAction", userAction, "tabUrl": tabUrl, "fromDomain": fromDomain, "toDomain": toDomain, "linkTextDomain": linkTextDomain, "reason": reason, url});
        document.querySelector("#nrg-clicks-extension-note").style.display = "none";
    }

    function handleOptionsClickPremium(target, userAction) {
    
        const tabUrl = window.location.href;        
        const hash = target.getAttribute("data-hash");
        const url = target.getAttribute("data-url");
        const reason = target.getAttribute("data-reason");

        browser.runtime.sendMessage({"action": "userActionPremium", userAction, tabUrl, hash, url, reason});                  
        document.querySelector("#nrg-clicks-extension-note").style.display = "none";
    }
    
    function setUntrustedDomainMessage(domain, blockingReasonId, linkTextDomain) {
    
        const messageEl = document.querySelector("#nrg-clicks-extension-note #nrg-message");
    
        if(messageEl) {
    
            messageEl.innerHTML = `
          We stopped this click because you were heading to "<b style="font-weight: bold!important;">${linkTextDomain || domain}</b>", which is unknown.`;
            messageEl.setAttribute("data-from", domain);
            messageEl.setAttribute("data-to", domain);
            messageEl.setAttribute("data-linktext", linkTextDomain || "");
            messageEl.setAttribute("data-reason", blockingReasonId);
            document.querySelector("#nrg-clicks-extension-note").style.display = "inline-block";
    
            document.querySelector("#nrg-clicks-extension-note #allow-once").innerHTML = `
          Allow this click temporarily`;
            document.querySelector("#nrg-clicks-extension-note #allow").innerHTML = `
          I want to trust "${linkTextDomain || domain}" from now on.`;
            document.querySelector("#nrg-clicks-extension-note #alternative").innerHTML = 'Open link safely (Norton customers only)';  
            document.querySelector("#nrg-clicks-extension-note #alternative").style.display = "inline";
        }
    
    }
    
    function setProtocolDowngradeMessage(fromDomain, toDomain, linkTextDomain, _fromRootDomain, toRootDomain) {
    
        const messageEl = document.querySelector("#nrg-clicks-extension-note #nrg-message");
    
        if(messageEl) {
    
            messageEl.innerHTML = `
          We stopped this click because we detected a non-secure connection heading to "${toRootDomain}".`;
            messageEl.setAttribute("data-from", fromDomain);
            messageEl.setAttribute("data-to", toDomain);
            messageEl.setAttribute("data-linktext", linkTextDomain || "");
            messageEl.setAttribute("data-reason", "4");
            document.querySelector("#nrg-clicks-extension-note").style.display = "inline-block";
    
            document.querySelector("#nrg-clicks-extension-note #allow-once").innerHTML = `
          Allow this click temporarily`;
            document.querySelector("#nrg-clicks-extension-note #allow").innerHTML = `
          I dont care about non-secure connections`;
            document.querySelector("#nrg-clicks-extension-note #alternative").style.display = "none";                  
        }
    
    }
    
    function setTrackingDomainMessage(fromDomain, toDomain, linkTextDomain, tracker, trackerDescription) {
    
        const messageEl = document.querySelector("#nrg-clicks-extension-note #nrg-message");
    
        if(messageEl) {
    
            messageEl.innerHTML = `
          We prevented <b style="font-weight: bold;!important" title="${trackerDescription || ""}">${tracker}</b> from tracking you by blocking this click.`;
            messageEl.setAttribute("data-from", fromDomain);
            messageEl.setAttribute("data-to", toDomain);
            messageEl.setAttribute("data-linktext", linkTextDomain || "");
            messageEl.setAttribute("data-reason", "1");
            document.querySelector("#nrg-clicks-extension-note").style.display = "inline-block";
    
            document.querySelector("#nrg-clicks-extension-note #allow-once").innerHTML = `
          Allow this click temporarily`;
            document.querySelector("#nrg-clicks-extension-note #allow").innerHTML = `
          I don't mind being tracked by "${tracker}"`;
            document.querySelector("#nrg-clicks-extension-note #alternative").innerHTML = "Open link privately (Norton customers only)";  
            document.querySelector("#nrg-clicks-extension-note #alternative").style.display = "inline";
    
        }
    
    }
    
    function domLoadedCallback() {

        console.log("Click Master is running.");
        
        setInterval(()=> {
    
            [].forEach.call(document.querySelectorAll("iframe[src]"), function(anIframe) {
                if(anIframe && anIframe.contentDocument)
                {
                    anIframe.contentDocument.addEventListener("click", clickedClickMaster, true);
                    anIframe.contentDocument.addEventListener("mousedown", clickedClickMaster, true);
                }
            });
    
            [].forEach.call(document.querySelectorAll("iframe:not([src])"), function(anIframe) {
                if(anIframe && anIframe.contentDocument && anIframe.getAttribute("src") === null)
                {
                    anIframe.contentDocument.addEventListener("click", clickedClickMaster, true);
                    anIframe.contentDocument.addEventListener("mousedown", clickedClickMaster, true);
                }
            });
        
        }, 1000);           
    }
        
    if(isClickContextAnIframe() === false)
    {    
        createMessagesPlaceholder();
        
        browser.runtime.onMessage.addListener(function(backMessage) {
                 
            if(backMessage.domloadedCallback) 
            {
                domLoadedCallback();
            }
            else
            if(backMessage.protect)
            {
                checkOpenerClickMaster(backMessage.protect);
            }
            else
            if(backMessage && !isNaN(backMessage.reason))
            {
                document.querySelector("#nrg-clicks-extension-note #nrg-message").setAttribute("data-hash", backMessage.clickedHash);
                document.querySelector("#nrg-clicks-extension-note #nrg-message").setAttribute("data-url", backMessage.clickedUrl);

                switch (backMessage.reason)
                {
                case 1 : {                                                     
                    setTrackingDomainMessage(backMessage.from, backMessage.to, backMessage.linkTextDomain || undefined,
                        backMessage.fromDomainDetails ? backMessage.fromDomainDetails.company : backMessage.fromRootDomain,
                        backMessage.fromDomainDetails ? backMessage.fromDomainDetails.description : "");
                }break;
                case 2 : {
                    setUntrustedDomainMessage(backMessage.from, backMessage.reason, backMessage.linkTextDomain || undefined); 
                }break;
                case 3 : {
                    setUntrustedDomainMessage(backMessage.to, backMessage.reason, backMessage.linkTextDomain || undefined); 
                }break;
                case 4 : {
                    setProtocolDowngradeMessage(backMessage.from,backMessage.to, backMessage.linkTextDomain || undefined,
                        backMessage.fromDomainDetails ? backMessage.fromDomainDetails.company : backMessage.fromRootDomain,
                        backMessage.toDomainDetails ? backMessage.toDomainDetails.company : backMessage.toRootDomain); 
                }break;
                }                                                          
            }
      
            return true;
            
        });
    }

})();