let dialerWindowId = null;

const DIALER_URL = 'dialer/dist/index.html';

function focusDialer() {
    if (dialerWindowId) {
        chrome.windows.update(dialerWindowId, { focused: true }); // Met au premier plan
    }
}

async function openDialer(reopen) {
    return  new Promise((resolve) => {
        chrome.windows.getAll({ populate: true }, (windows) => {

            for (let win of windows) {
                if (win.tabs?.[0]?.url === `chrome-extension://${chrome.runtime.id}/${DIALER_URL}`) {
                    dialerWindowId = win.id;
                }
                if (win.id === dialerWindowId) { // Vérifie si c'est notre fenêtre dialer
                    found = true;
                    focusDialer();
                    if (reopen) {
                        chrome.tabs.update(win.tabs[0].id, { url: DIALER_URL });
                    }
                    resolve(win.tabs[0]);
                    return;
                }

            }
            // Si aucune fenêtre dialer n'existe, crée une nouvelle
            chrome.windows.create({
                url: DIALER_URL,
                type: 'popup',
                width: 1200,
                height: 800
            }, (win) => {
                dialerWindowId = win.id; // Stocker l'ID de la nouvelle fenêtre
                resolve(win.tabs[0]);
            });
        });
    });
}

function openTabAuth() {
    chrome.tabs.create({
        url: 'https://workspace.aircall.io',
        active: true // met l’onglet au premier plan
    });
}


let resolveCheckReady = [];

async function checkDialerReady() {
    return new Promise(resolve => {
        resolveCheckReady.push(resolve);
        chrome.runtime.sendMessage({ action: "check_dialer_ready" });
    });
}

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
    if (message.action === "openDialer") {
        openDialer(true);
        sendResponse({ status: "Dialer ouvert" });
    }
    if (message.action === "openTabAuth") {
        openTabAuth(true);
        sendResponse({ status: "Tab auth ouvert" });
    }

    if (message.action === 'air_call_call_contact') {
        await openDialer();
        await checkDialerReady();
        console.log('DIALER READY')
        chrome.runtime.sendMessage({ action: "air_call_dialer_call_contact", contact: message.contact });
    }

    if (message.action === 'air_call_list_number') {
        await openDialer();
        await checkDialerReady();
        console.log('DIALER READY')
        chrome.runtime.sendMessage({ action: "air_call_list_register", list: message.list, append: message.append });
    }

    if (message.action === 'dialer_ready') {
        resolveCheckReady.forEach(cb => cb());
        resolveCheckReady = [];
    }
});
