import { ensureFileSync } from "$std/fs/ensure_file.ts";
import { IS_BROWSER } from "$fresh/runtime.ts";
import { MCGrizzConf } from "../types/mcgrizzconf.ts";

const defaultConf: MCGrizzConf = {
  loader: 'unset',
  version: ''
}

const confPath = 'mcgrizz.json'

export function makeConfFile(): MCGrizzConf {

  Deno.writeTextFileSync(confPath, JSON.stringify(defaultConf, null, 2), {create: true});
  
  return defaultConf;
}

export function getConfFile(): MCGrizzConf {
  if (IS_BROWSER) return defaultConf;
  ensureFileSync(confPath);
  const conf = JSON.parse(Deno.readTextFileSync(confPath) || 'null');

  if (!conf) {
    return makeConfFile();
  }

  return conf;
}

export async function updateConfFile(newConf: Partial<MCGrizzConf>) {
  if (IS_BROWSER) return;
  const conf = {...getConfFile(), ...newConf};

  await Deno.writeTextFile(confPath, JSON.stringify(conf, null, 2));
}
