(async () => {
window.psshs=[];
window.requests=[];
window.bodys=[];
window.targetIds=[];
window.pageURL="";
window.clearkey="";
// Ajouter un tableau pour stocker les MPD
window.detectedMPDs = window.detectedMPDs || [];

chrome.storage.local.get("isBlock", (value) => {
    window.isBlock = value.isBlock;
})

function convertHeaders(obj){
    return JSON.stringify(Object.fromEntries(obj.map(header => [header.name, header.value])))
}

window.blockRules = await fetch("blockRules.conf").then((r)=>r.text());
window.blockRules = window.blockRules.replace(/\n^\s*$|\s*\/\/.*|\s*$/gm, "").split("\n");

function testBlock(url) {
    return window.isBlock && window.blockRules.some(e => url.includes(e));
}

// Fonction badge simple
function updateBadge() {
    const browserAction = chrome.action || chrome.browserAction;
    if (!browserAction) return;
    
    const hasContent = (window.psshs && window.psshs.length > 0) || (window.clearkey && window.clearkey.length > 0);
    const hasMPD = window.detectedMPDs && window.detectedMPDs.length > 0;
    
    if (hasContent && hasMPD) {
        browserAction.setBadgeText({ text: detectedMPDs.length.toString() });
        browserAction.setBadgeBackgroundColor({ color: "#22c55e" });
    } else if (hasContent) {
        browserAction.setBadgeText({ text: "!" });
        browserAction.setBadgeTextColor({ color: "#fd7e14" });
    } else {
        browserAction.setBadgeText({ text: "" });
    }
}

//Get URL and headers from POST requests
chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        if (details.method === "POST") {
            if (!window.bodys)
                window.bodys=[];
            
            // Vérifier que le body existe dans window.bodys avant d'y accéder
            const bodyData = window.bodys.find((b) => b.id == details.requestId);
            
            window.requests.push({
                url:details.url,
                headers:convertHeaders(details.requestHeaders),
                body: bodyData ? bodyData.body : "" // Utiliser une chaîne vide si pas de body trouvé
            });
            
            if(testBlock(details.url)){
                return {cancel:true}
            }
        }
    },
    {urls: ["<all_urls>"]},
    ["requestHeaders", "blocking"]
);

//Get requestBody from POST requests
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        // Code existant pour les POST - avec vérification du requestBody
        if (details.method === "POST") {
            if (!window.bodys)
                window.bodys=[];
            
            // Vérifier que requestBody existe et a la propriété raw
            let bodyContent = "";
            if (details.requestBody && details.requestBody.raw && details.requestBody.raw.length > 0) {
                try {
                    bodyContent = btoa(String.fromCharCode(...new Uint8Array(details.requestBody.raw[0]['bytes'])));
                } catch (e) {
                    console.warn("Erreur lors de l'encodage du body:", e);
                    bodyContent = "";
                }
            }
            
            window.bodys.push({
                body: bodyContent,
                id: details.requestId
            });
        }
        
        // Nouveau : capturer les MPD (pour toutes les méthodes)
        if (details.url.includes('.mpd') || 
            details.url.includes('manifest') || 
            details.url.includes('dash.mpd') ||
            details.url.match(/\.(mpd|m3u8)(\?|$)/)) {
            
            if (!window.detectedMPDs.includes(details.url)) {
                window.detectedMPDs.push(details.url);
                console.log('MPD detected:', details.url);
                updateBadge(); // Mettre à jour badge
            }
        }
    },
    {urls: ["<all_urls>"]},
    ["requestBody"]
);

//Receive PSSH from content.js
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        switch(request.type){
            case "RESET":
                location.reload()
                break;
            case "PSSH":
                window.psshs.push(request.text)
                window.pageURL=sender.tab.url
                window.targetIds=[sender.tab.id, sender.frameId]
                updateBadge(); // Mettre à jour badge
                break;
            case "CLEARKEY":
                window.clearkey=request.text
                updateBadge(); // Mettre à jour badge
                break;
        }
    }
);

} )()

chrome.browserAction.onClicked.addListener(tab => {
    if(chrome.windows){
        chrome.windows.create({
            url: "popup/main.html",
            type: "popup",
            width: 1200,
            height: 800
        });
    } else {
        chrome.tabs.create({url: 'popup/main.html'})
    }
});

function createMenu(){
    chrome.storage.local.set({'isBlock': false}, null);
    chrome.contextMenus.create({
        id: "toggleBlocking",
        title: "Enable License Blocking"
    });
}

chrome.runtime.onInstalled.addListener(createMenu)
chrome.runtime.onStartup.addListener(createMenu)

chrome.contextMenus.onClicked.addListener(item => {
    if(item.menuItemId == "toggleBlocking"){
        chrome.storage.local.get("isBlock", (value) => {
            if(value.isBlock){
                chrome.storage.local.set({'isBlock': false}, null);
                chrome.contextMenus.update("toggleBlocking",{title: "Enable License Blocking"})
            } else {
                chrome.storage.local.set({'isBlock': true}, null);
                chrome.contextMenus.update("toggleBlocking",{title: "Disable License Blocking"})
            }
        })
    }
})