import { functions } from '../functions.js';
import { Kolotibablo } from "/js/content_scripts/kolotibablo.js";
import { ProxyGate } from "/js/content_scripts/proxygate.js";
import { RecaptchaV2 } from "/js/content_scripts/captchas/recaptchav2.js";
import { Hcaptcha } from "/js/content_scripts/captchas/hcaptcha.js";
import { Recaptchav2BFrame } from "/js/content_scripts/captchas/recaptchav2bframe.js";
import { AntiGate } from "/js/content_scripts/captchas/antigate.js";
import { Funcaptcha } from "/js/content_scripts/captchas/funcaptcha.js";


const contentScriptMatching = [
    {
        hosts: ["http://bropanel-rm.com", "https://docker.kolotibablo.com", "https://staging.kolotibablo.com", "https://kolotibablo.com"
            //, "http://localhost:3000" enable for local debugging
        ],
        module: Kolotibablo
    },{
        hosts: ["https://www.google.com/recaptcha/api2/anchor", "https://www.google.com/recaptcha/enterprise/anchor"],
        module: RecaptchaV2
    },{
        hosts: ["https://www.google.com/recaptcha/api2/bframe", "https://www.google.com/recaptcha/enterprise/bframe"],
        module: Recaptchav2BFrame
    },{
        hosts: ["https://newassets.hcaptcha.com/captcha/v1/"],
        module: Hcaptcha
    },{
        hosts: ["*.arkoselabs.com"],
        module: Funcaptcha
    },{
        hosts: ["%PROXYGATE%"],
        module: ProxyGate
    },{
        hosts: ["%ANTIGATE%"],
        module: AntiGate
    }
];

let currentTask = null;

async function matchRouter(currentTask) {

    for (const record of contentScriptMatching) {
        const matchingHosts = record.hosts.filter(function (host) {

            //match all or specific href
            if (document.location.href.indexOf(host) === 0) return true; //specific url match
            if (host.indexOf("%PROXYGATE%") !== -1 && currentTask && currentTask.website_url && currentTask.queue_id !== 25) {
                const parsed = functions.parseUrl(currentTask.website_url);
                return parsed.hostname === document.location.host;
            }
            if (host.indexOf("%ANTIGATE%") !== -1 && currentTask && currentTask.queue_id === 25 && document.location.href !== 'about:blank') {
                return true;
            }
            if (host === "*") return true; //match all
            if (host.indexOf("*") !== -1 && functions.isUrlMatchingAstericsPattern(document.location.href, host)) {
                return true;
            }
            return false;
        });
        if (matchingHosts.length > 0) {
            const controller = new record.module();
            functions.debugOut('Router', 'matched hosts at ' + document.location.href, controller.toString(), matchingHosts, 4);
            if (await controller.run() === false) continue;
            if (typeof controller.backgroundListenerHandler === "function") {
                chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
                    return await controller.backgroundListenerHandler(request, sender, sendResponse);
                });
            }
            if (typeof controller.pageListenerHandler === "function") {
                window.addEventListener("message", async function (message) {
                    return controller.pageListenerHandler(message);
                });
            }
            if (typeof controller.intervalTask === "function") {
                clearInterval(controller.intervalTaskId);
                controller.intervalTaskId = null;
                controller.intervalTaskId = setInterval(() => {
                    controller.intervalTask();
                }, controller.intervalValue);
            }
            break;

        }

    }

}

async function insertFingerprint() {
    const options = await functions.getOptions();
    if (!options.is_fingerprint_set) return;
    for (let parameter in options.current_fingerprint) {
        const value = options.current_fingerprint[parameter];
        parameter = parameter.replace('self__', '');
        if (parameter.indexOf('navigator') !== -1) {
            parameter = parameter.split(".")[1];
            Object.defineProperty(navigator, parameter, {
                get:() => value,
                configurable: true,
                enumerable: true,
            });
        }
    }
}

(async() => {

    currentTask = await functions.sendMessage({ type: 'getCurrentTask' });
    if (!currentTask) {
        return;
    }
    if (!currentTask.useDefaultUserAgent) {
        await insertFingerprint();
    }
    await matchRouter(currentTask);
})();


