import fs from "fs";
import path from "path";

import { info } from "../log.js";

// TODO: Maybe add 'packages' later on
export type XwebConfig = {
    use: {
        inline: boolean,
        tags: boolean
    },
    folder: {
        src: string,
        out: string,
        tags: string
    },
    extension: {
        src: string,
        out: string
    },
    inline?: {
        from: {
            start: string,
            end: string
        },
        to: {
            start: string,
            end: string
        }
    },
    tags: string[]
}

export function read_config(executer = "run/config"): XwebConfig {
    let CONFIG: XwebConfig = {
        folder: {
            src: "./src",
            out: "./out",
            tags: "./xweb_tags"
        },
        extension: {
            src: ".xweb",
            out: ".html"
        },
        use: {
            inline: true,
            tags: true
        },
        inline: {
            from: {
                start: "{{",
                end: "}}"
            },
            to: {
                start: "<?=",
                end: "?>"
            }
        },
        tags: []
    };
    const CONFIG_FILE_PATH = path.join(process.cwd(), "xwebconfig.json");
    if (fs.existsSync(CONFIG_FILE_PATH)) {
        info(executer, "Config file found");
        const CONFIG_FILE_CONTENT = fs.readFileSync(CONFIG_FILE_PATH, "utf8");
        CONFIG = JSON.parse(CONFIG_FILE_CONTENT);
    } else {
        info(executer, "No config file found. Using default config");
    }
    return CONFIG;
}

export function save_config(executer: string, config: XwebConfig) {
    const CONFIG_FILE_PATH = path.join(process.cwd(), "xwebconfig.json");
    fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(config, null, 4));
    info(executer, "Saved xwebconfig.json");
}