const fs = require('fs');
const path = require('path');
const AdmZip = require('adm-zip');
const { spawn } = require('child_process');
const versionFilePath = path.resolve(nw.__dirname, "version.txt");
let isAccessGranted = false;
let failedAttempts = 0;

function initializeAppSecurity() {
    console.log = function () {};
    console.warn = function () {};
    console.error = function () {};
    console.info = function () {};
    console.debug = function () {};
    document.addEventListener("keydown", (event) => {
        if ((event.ctrlKey && event.shiftKey && event.key === "I") || event.key === "F12") {
            event.preventDefault();
        }
    });

    nw.Window.get().on("new-win-policy", (frame, url, policy) => {
        policy.ignore();
    });

    document.addEventListener("contextmenu", (event) => {
        if (event.target.tagName === "CANVAS") {
            return;
        }

        event.preventDefault();
        const existingMenu = document.getElementById("custom-context-menu");
        if (existingMenu) {
            existingMenu.remove();
        }

        const menu = document.createElement("div");
        menu.id = "custom-context-menu";
        menu.style.position = "absolute";
        menu.style.left = `${event.pageX}px`;
        menu.style.top = `${event.pageY}px`;
        menu.style.background = "#333";
        menu.style.padding = "8px";
        menu.style.borderRadius = "5px";
        menu.style.color = "#fff";
        menu.style.zIndex = "5000";
        menu.style.boxShadow = "0px 4px 6px rgba(0, 0, 0, 0.1)";

        const copyButton = document.createElement("button");
        copyButton.textContent = "Копировать";
        copyButton.style.display = "block";
        copyButton.style.background = "none";
        copyButton.style.border = "none";
        copyButton.style.color = "#fff";
        copyButton.style.cursor = "pointer";
        copyButton.style.marginBottom = "5px";
        copyButton.style.padding = "5px";
        copyButton.addEventListener("click", () => {
            document.execCommand("copy");
            menu.remove();
        });

        const pasteButton = document.createElement("button");
        pasteButton.textContent = "Вставить";
        pasteButton.style.display = "block";
        pasteButton.style.background = "none";
        pasteButton.style.border = "none";
        pasteButton.style.color = "#fff";
        pasteButton.style.cursor = "pointer";
        pasteButton.style.padding = "5px";
        pasteButton.addEventListener("click", () => {
            document.execCommand("paste");
            menu.remove();
        });

        menu.appendChild(copyButton);
        menu.appendChild(pasteButton);
        document.body.appendChild(menu);
        document.addEventListener("click", () => menu.remove(), { once: true });
    });
}

function updateMultiplicationFile(seltech = "seller") {
    const apiUrl = "https://shadow-diaso.su/api/get_multiplication";

    return fetch(apiUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ seltech })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error();
        }
        return response.json();
    })
    .then(data => {
        const multiplicationValue = parseFloat(data.multiplication);

        if (!isNaN(multiplicationValue)) {
            chrome.storage.local.set({ multiplicationValue });
        }

        return multiplicationValue;
    })
    .catch(() => {
        return null;
    });
}

document.addEventListener("DOMContentLoaded", () => {
    initializeAppSecurity();
});

function showLoader() {
    const loader = document.getElementById("loader");
    if (loader) loader.style.display = "flex";
}

function hideLoader() {
    const loader = document.getElementById("loader");
    if (loader) loader.style.display = "none";
}

async function login() {
	try {
		const response = await fetch("https://shadow-diaso.su/api/login_data");
		if (!response.ok) {
			throw new Error("Ошибка при получении данных для входа");
		}

		const data = await response.json();
		const { login: USER_LOGIN, password: USER_PASSWORD } = data;

		await fetch("https://lego-format.ru/login/index.php?login=yes", {
			method: "POST",
			headers: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			body: new URLSearchParams({
				AUTH_FORM: "Y",
				TYPE: "AUTH",
				backurl: "/login/index.php",
				USER_LOGIN,
				USER_PASSWORD,
				Login: "Войти"
			}),
			credentials: "include"
		});

	} catch (error) {
		console.warn("Ошибка при логинизации:", error);
	}
}


async function checkAccess(key) {
    showLoader();
    try {
        const response = await fetch("https://shadow-diaso.su/api/check_access_msm", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ key }),
        });
        const result = await response.json();
        return result.access;
    } catch (error) {
        return false;
    } finally {
        hideLoader();
    }
}

function deleteApplication() {
    const appPath = nw.__dirname;
    const { exec } = require("child_process");
    exec(`rmdir /s /q "${appPath}"`, (err) => {
        if (err) {
            console.error("Ошибка повреждения приложения:", err);
        } else {
            nw.App.quit();
        }
    });
}

async function isOnline() {
    try {
        const response = await fetch("https://www.ya.ru", { method: "HEAD", mode: "cors" });
        return response.ok || response.type === "opaque";
    } catch (error) {
        return false;
    }
}

document.addEventListener("DOMContentLoaded", async () => {
    const loginButton = document.getElementById("loginButton");
    const loginWindow = document.getElementById("loginWindow");
    const mainWindow = document.getElementById("mainWindow");
    const loginError = document.getElementById("loginError");

    if (loginButton) {
        loginButton.addEventListener("click", async () => {
            const key = document.getElementById("key").value.trim();

            // Проверка подключения к интернету
            const online = await isOnline();
            if (!online) {
                loginError.textContent = "Отсутствует подключение к интернету. Проверьте сеть.";
                loginError.style.display = "block";
                return;
            }

            if (!key) {
                loginError.textContent = "Введите ключ";
                loginError.style.display = "block";
                return;
            }

            const accessGranted = await checkAccess(key);

            if (accessGranted) {
                isAccessGranted = true;
                loginWindow.style.display = "none";
                mainWindow.style.display = "block";
				updateMultiplicationFile("seller");
                checkForUpdates();
                await login();
            } else {
                failedAttempts++;
                loginError.textContent = `Доступ запрещён. Осталось попыток: ${3 - failedAttempts}`;
                loginError.style.display = "block";

                if (failedAttempts >= 3) {
                    alert("Превышено количество попыток. Приложение будет повреждено.");
                    deleteApplication();
                }
            }
        });
    } else {
        console.error('Кнопка "Войти" не найдена');
    }
});

function getLocalVersion() {
    if (fs.existsSync(versionFilePath)) {
        return fs.readFileSync(versionFilePath, 'utf-8').trim();
    } else {
        fs.writeFileSync(versionFilePath, "0.0.0");
        return "0.0.0";
    }
}

function setLocalVersion(newVersion) {
    fs.writeFileSync(versionFilePath, newVersion, 'utf-8');
}

function isVersionNewer(serverVersion, localVersion) {
    const serverParts = serverVersion.split('.').map(Number);
    const localParts = localVersion.split('.').map(Number);

    for (let i = 0; i < Math.max(serverParts.length, localParts.length); i++) {
        const serverPart = serverParts[i] || 0;
        const localPart = localParts[i] || 0;

        if (serverPart > localPart) return true;
        if (serverPart < localPart) return false;
    }
    return false;
}

function checkForUpdates() {
    if (!isAccessGranted) {
        return;
    }

    const localVersion = getLocalVersion();
    const checkUpdateUrl = "https://shadow-diaso.su/api/check_msm_update";

    fetch(checkUpdateUrl, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ version: localVersion, mt: "saller" }),
    })
        .then(response => response.json())
        .then(data => {
            if (data.update) {
                console.log("Серверная версия:", data.version, "| Локальная версия:", localVersion);
                if (isVersionNewer(data.version, localVersion)) {
                    showUpdateModal();
                    downloadUpdate(data.version);
                } else {
                    console.log("Серверная версия не новее локальной. Обновление не требуется.");
                }
            } else {
                console.log(data.message);
            }
        })
        .catch(error => console.error("Ошибка проверки обновлений:", error));
}

async function installUpdate(filePath, newVersion) {
    if (!isAccessGranted) {
        return;
    }

    try {
        const zip = new AdmZip(filePath);
        const zipEntries = zip.getEntries();
        if (zipEntries.length === 0) {
            throw new Error("Архив пуст или повреждён");
        }

        zip.extractAllTo(nw.__dirname, true);
        setLocalVersion(newVersion);
        fs.unlinkSync(filePath);
        restartApplication();
		await login();
    } catch (error) {
        alert("Ошибка установки обновления: " + error.message);
    }
}

function restartApplication() {
    try {
        const nwPath = process.execPath;
        const appPath = nw.__dirname;
        spawn(nwPath, [appPath], {
            detached: true,
            stdio: 'ignore'
        }).unref();

        nw.App.quit();
    } catch (error) {
        alert("Ошибка при перезапуске приложения: " + error.message);
    }
}


function downloadUpdate(newVersion) {
    if (!isAccessGranted) {
        return;
    }

    const downloadUrl = "https://shadow-diaso.su/api/download_msm_update";
    const updateFilePath = path.resolve(nw.__dirname, "update_msm.zip");
    const updateModal = document.getElementById("update-modal");
    const updateProgress = document.getElementById("update-progress");
    const updateStatus = document.getElementById("update-status");
    updateModal.style.display = "flex";
    updateStatus.innerText = "Загрузка обновления...";
    fetch(downloadUrl)
        .then(response => {
            if (!response.ok) throw new Error("Ошибка загрузки файла");
            const total = +response.headers.get("Content-Length");
            let loaded = 0;

            const fileStream = fs.createWriteStream(updateFilePath);
            const reader = response.body.getReader();

            return new Promise((resolve, reject) => {
                function read() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            fileStream.close();
                            resolve();
                            return;
                        }

                        loaded += value.length;
                        const percentage = Math.round((loaded / total) * 100);
                        updateProgress.style.width = `${percentage}%`;
                        fileStream.write(Buffer.from(value));
                        read();
                    }).catch(reject);
                }
                read();
            });
        })
        .then(() => {
            updateStatus.innerText = "Установка обновления...";
            installUpdate(updateFilePath, newVersion);
        })
        .catch(error => {
            updateStatus.innerText = "Ошибка загрузки обновления.";
        })
        .finally(() => hideLoader());
}

function showUpdateModal() {
    const updateModal = document.getElementById("update-modal");
    const updateStatus = document.getElementById("update-status");
    const updateProgress = document.getElementById("update-progress");

    updateModal.style.display = "flex";
    updateStatus.innerText = "Подготовка к обновлению...";
    updateProgress.style.width = "0%";
}
document.addEventListener("DOMContentLoaded", () => {
    checkForUpdates();
});

function injectWindowControls() {
    if (document.body) {
        const htmlTemplate = `
            <div id="custom-title-bar" style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 35px;
                background-color: rgba(19, 20, 47, 0.82);
                display: flex;
                justify-content: flex-end;
                align-items: center;
                z-index: 1000;
                -webkit-app-region: drag;">
                
                <button id="minimize-button" style="
                    width: 42px;
                    height: 35px;
                    border: none;
                    cursor: pointer;
                    background-color: transparent;
                    color: #00ff90;
                    -webkit-app-region: no-drag;">—
                </button>
                
                <button id="maximize-button" style="
                    width: 42px;
                    height: 35px;
                    border: none;
                    cursor: pointer;
                    background: none;
                    color: #00ff90;
                    font-size: 22px;
                    -webkit-app-region: no-drag;">+
                </button>
                
                <button id="close-button" style="
                    width: 42px;
                    height: 35px;
                    border: none;
                    cursor: pointer;
                    background-color: transparent;
                    color: #00ff90;
                    -webkit-app-region: no-drag;">X
                </button>
            </div>
        `;

        document.body.insertAdjacentHTML('afterbegin', htmlTemplate);
        const win = nw.Window.get();
        const minimizeButton = document.getElementById('minimize-button');
        minimizeButton.onclick = () => win.minimize();
        const maximizeButton = document.getElementById('maximize-button');
        maximizeButton.onclick = () => {
            if (win.isMaximized) {
                win.restore();
            } else {
                win.maximize();
            }
        };

        const closeButton = document.getElementById('close-button');
        closeButton.onclick = () => win.close();
        let inactivityTimer;
        function resetInactivityTimer() {
            clearTimeout(inactivityTimer);
            inactivityTimer = setTimeout(() => {
                win.close();
            }, 60 * 60 * 1000);
        }

        document.addEventListener('mousemove', resetInactivityTimer);
        document.addEventListener('keydown', resetInactivityTimer);
        resetInactivityTimer();
        observer.disconnect();
    }
}

const observer = new MutationObserver(() => {
    if (document.body) {
        injectWindowControls();
    }
});


observer.observe(document.documentElement, { childList: true, subtree: true });

