import { error, info } from "../log.js";
import { XwebConfig } from "../config/config.js";

import fetch, { Response } from "node-fetch";
import path from "path";
import fs from "fs";

export function is_bad_response(executer: string, tag_name: string, response: Response): boolean {
    if (!response.ok) {
        error(executer, `Error while fetching tagset '${tag_name}'. Error code ${response.status}`);
        return true;
    }
    return false;
}

export function save_tagsets(executer: string, tagset_list: string[], config: XwebConfig) {
    let ready = 0;
    tagset_list.forEach(async (tag_name: string) => {
        info(executer, `Fetching tagset ${ready + 1}/${tagset_list.length} '${tag_name}'`);
        const FETCH_URL = `https://raw.githubusercontent.com/CodeBoy124/xweb-tagsets/main/${tag_name}.js`;
        const RESPONSE = await fetch(FETCH_URL);
        if (is_bad_response(executer, tag_name, RESPONSE)) return;
        const CONTENT = await RESPONSE.text();
        const TAGSET_FILE_PATH = path.join(process.cwd(), config.folder.tags, tag_name + ".js");
        fs.writeFileSync(TAGSET_FILE_PATH, CONTENT);
        info(executer, `Finished adding tagset ${ready + 1}/${tagset_list.length} '${tag_name}'`);
        ready++;
    });
}