import createDefaultPack from "./create-default-pack.js";
import {
    PackAbsolutPathToJson,
    PackAuthor,
    PackFolderName,
    packFor,
    packFromDatabaseT,
    packFromJSON,
    PackName,
    PackOrigin
} from "../../../src/types/pack";
import {HOST} from "../../../src/types/config";
import createDefaultPackJson from "./packs/create-default-json.js";
import PACKS_CONFIG, {DefaultCategorySettings, VideoWithThumbnails} from "./packs/packs-config.js";
import {CurrentVersion} from "../../../src/Components/PluginNeedUpdate/types/types";
import {
    FileForDatabase,
    PackExisted,
    PackSuccessfullyInstalled
} from "../../../src/Components/ModalInstall/types/types";

const packs: Partial<packFromDatabaseT>[] = [
    PACKS_CONFIG["Settings in SubCategory"].packFromDatabase,
    PACKS_CONFIG["Links"].packFromDatabase,
    PACKS_CONFIG["Preview fix"].packFromDatabase,

    PACKS_CONFIG[DefaultCategorySettings].packFromDatabase,
    // PACKS_CONFIG[VideoWithThumbnails].packFromDatabase,
    // PACKS_CONFIG["Many Categories"].packFromDatabase,

    PACKS_CONFIG["SFX compatible"].packFromDatabase,
    PACKS_CONFIG["SFX compatible 2"].packFromDatabase,
    // PACKS_CONFIG["SFX default Emerald"].packFromDatabase,
    PACKS_CONFIG["Sound pack"].packFromDatabase,
    PACKS_CONFIG["Settings on Pack Level"].packFromDatabase,
    PACKS_CONFIG["Settings on Pack Level 2"].packFromDatabase,
]

const ALL_PACKS = packs.map(pack => createDefaultPack(pack))

async function getPacks(): Promise<packFromDatabaseT[]> {
    return ALL_PACKS
}

window.getPacks = getPacks

window.getHost = (): HOST => "PPRO"
window.getPluginVersion = (): CurrentVersion => "4.0.0"

function getPreset(path: PackAbsolutPathToJson): packFromJSON {
    const pack = ALL_PACKS.find(pack => pack.path === path)

    if (!pack) throw new Error(`Pack with path ${path} not found`)

    const candidate = PACKS_CONFIG[pack.name]
    if (candidate) {
        return createDefaultPackJson(pack, candidate.categories, candidate.packFromDatabase.settings, candidate.packFromDatabase.origin, candidate.packFromDatabase.markers)
    }

    return createDefaultPackJson(pack)
}

window.getPreset = getPreset

async function applyVideo(arg: any): Promise<void> {

    console.log(arg)


    const isError = false
    if (isError) {
        setTimeout(() => {
            window.dispatchEvent(new CustomEvent('errorInUpload', {
                detail: { text: "Error in upload" }
            }))
        }, 1000)

    }else {
        setTimeout(() => {
            window.dispatchEvent(new CustomEvent('successInUpload', {
                detail: { text: "Event Successfully Uploaded" }
            }))
        }, 1000)
    }
}

window.applyVideo = applyVideo

async function vPr(packName: PackName, packAuthor: PackAuthor, path: PackAbsolutPathToJson, packFolderName: PackFolderName, origin: PackOrigin): Promise<any>{
    const isError = false

    return !isError
}

window.vPr = vPr


function getSeparator() {
    return "\\"
}
window.getSeparator = getSeparator;

function onClickOpenUrlInDefaultBrowser(url: string) {
    window.open(url, '_blank');
}

window.onClickOpenUrlInDefaultBrowser = onClickOpenUrlInDefaultBrowser

async function installPack(file: FileForDatabase[]): Promise<PackSuccessfullyInstalled | PackExisted> {
    // Симуляция проверки существования пакета
    const packExists = false; // Здесь можно добавить реальную логику проверки

    if (packExists) {
        const packExisted: PackExisted = {
            status: "exists",
            packExistedPath: "D:\\temp\\MotionBro\\SFX compatible_by_Videolancer",
            currentVersion: "1.0.0",
            newVersion: "1.0.0",
            packPath: "D:\\temp\\MotionBro\\SFX compatible_by_Videolancer",
            archiveName: "SFX compatible_by_Videolancer",
            packActualName: "SFX compatible",
            message: "Pack is already installed."
        };
        return packExisted; // Немедленный возврат, если пакет уже существует
    }

    // take random pack from pack
    function getRandomPack(packs: Partial<packFromDatabaseT>[]): Partial<packFromDatabaseT> | undefined {
        if (packs.length === 0) return undefined;
        const randomIndex = Math.floor(Math.random() * packs.length);
        return packs[randomIndex];
    }

    const randomPack = getRandomPack(ALL_PACKS);


    // Если пакет не существует, симулируем установку с задержкой 15 секунд
    return new Promise<PackSuccessfullyInstalled>((resolve) => {
        setTimeout(() => {
            const packInstallSuccess: PackSuccessfullyInstalled = {
                status: "success",
                message: "Pack has been installed",
                info: {
                    packName: randomPack?.name || "Many Categories",
                    version: "1.0.0",
                    author: "Videolancer",
                    packFolderName: randomPack?.packFolderName || "Many_Categories_Videolancer",
                    origin: undefined,
                },
                needVerification: true
            };
            resolve(packInstallSuccess);
        }, 15000); // Задержка 15 секунд
    });
}

// Экспонирование функции для глобального доступа (например, для тестирования)
(window as any).installPack = installPack;

async function uninstallPack(packFolderName: PackFolderName){
    return {
        status: "success",
        message: "Pack has been uninstalled"
    }
}

(window as any).uninstallPack = uninstallPack


async function rJB(packFolderName: PackFolderName, host: packFor){
    return "jsxbinString"
}

window.rJB = rJB

function eJB(jsxbinString: string){

}
window.eJB = eJB

function getInstallationPath(): Promise<string> {
    return Promise.resolve("D:\\temp\\MotionBro")
}
window.getInstallationPath = getInstallationPath