import { ArgumentsCamelCase } from "yargs";
import { read_config, save_config } from "../config/config.js";
import { error, info, warn } from "../log.js";
import path from "path";
import fs from "fs";

export default async function run(argv: ArgumentsCamelCase<{
    y: boolean;
} & {
    names: string | undefined;
}>) {
    const CONFIG = read_config("remove/config");
    if (!CONFIG.use.tags) {
        error("remove/config", "Cannot remove tagset in a project that has disabled tagsets");
        return;
    }
    if (argv.names == undefined) {
        error("remove/config", "Cannot remove tagsets without a name");
        return;
    }
    const TAGSET_NAMES: string[] = argv.names?.split(" ") as string[];
    for (const REMOVE_NAME of TAGSET_NAMES) {
        const INDEX_OF_TAGSET = CONFIG.tags.indexOf(REMOVE_NAME);
        // if tag has not been added, warn and skip the rest
        if (INDEX_OF_TAGSET < 0) {
            await warn("remove/config", `Tagset ${REMOVE_NAME} isn't added in xwebconfig.json`, argv.y);
            continue;
        }
        CONFIG.tags.splice(INDEX_OF_TAGSET, 1);
    }
    save_config("remove/config", CONFIG);

    let ready = 0;
    for (const TAG_NAME of TAGSET_NAMES) {
        info("remove/file", `Removing tagset ${ready + 1}/${CONFIG.tags.length} '${TAG_NAME}'`);
        const TAGSET_FILE_PATH = path.join(process.cwd(), CONFIG.folder.tags, TAG_NAME + ".js");

        // if file does not exist, warn and skip rest
        if (!fs.existsSync(TAGSET_FILE_PATH)) {
            await warn("remove/file", `File for tagset '${TAG_NAME}' does not exist`, argv.y);
            continue;
        }

        fs.unlinkSync(TAGSET_FILE_PATH);
        info("remove/file", `Finished removing tagset ${ready + 1}/${CONFIG.tags.length} '${TAG_NAME}'`);
        ready++;
    }
}