import Seven = require('node-7z');
import { existsSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'fs';
import fetch from 'node-fetch';
import { resolve } from 'path';
import sevenBin = require('7zip-bin');

const dir = resolve(__dirname, '..');
console.log("Downloading and installing Anime4k");
( async () => {
    let zipURL = "";
    // REMOVE EXISTING 4K
    if (existsSync(dir + "/anime4k")) rmdirSync(dir + "/anime4k", {recursive: true});

    // URL PLATFORM
    if (process.platform == "win32") zipURL = "https://github.com/TianZerL/Anime4KCPP/releases/download/v2.5.0/Anime4KCPP_CLI-2.5.0-Win64-msvc.7z";
    else throw new Error("This lib not support " + process.platform);

    // DOWNLOAD 4K
    const zipRes = await fetch(zipURL);
    const zip = await zipRes.buffer();

    // INSTALL 4K
    writeFileSync(resolve(dir, "zip.7z"), zip);

    Seven.extractFull(resolve(dir, "zip.7z"), resolve(dir), {
        $bin: sevenBin.path7za,
        yes: true
    }).on("end", () => {
        unlinkSync(dir + "/zip.7z");

        // RENAME FOLDER
        renameSync(dir + "/CLI", dir + "/anime4k")/** */
    })

    

})()