#!/usr/bin/env node

const fs = require("fs");
const path = require("path");
const argv = require("yargs").argv;

export default () => {
  /**
   * @param {string} src  The path to the thing to copy.
   * @param {string} dest The path to the new copy.
   * @param {string} lng Get Language
   */
  const addLanguage = (src: string, dest: string, lng: string) => {
    const exists = fs.existsSync(src);
    const stats = exists && fs.statSync(src);
    const isDirectory = exists && stats.isDirectory();
    if (isDirectory) {
      fs.mkdirSync(dest);
      fs.readdirSync(src).forEach((childItemName: string) => {
        addLanguage(
          path.join(src, childItemName),
          path.join(dest, childItemName),
          lng
        );
      });

      console.log(
        "\x1b[32m%s\x1b[0m",
        `\n✓ Added language option ${lng.toUpperCase()}.\nDon't forget to translate '${lng.toUpperCase()}' translation files inside 'public/locales/${lng.toUpperCase()}'\n`
      );

      console.log("\x1b[33m%s\x1b[0m", "Project Zero - Akinon\n");
    } else {
      fs.copyFileSync(src, dest);
    }
  };

  const i18nDocumentUpdate = (lng: string) => {
    /* next-i18next.config.js */
    const workingDir = path.resolve(process.cwd());

    const i18nPath = path.resolve(workingDir, "next-i18next.config.js");

    if (!fs.existsSync(i18nPath)) {
      return;
    }

    const i18nData = fs.readFileSync(i18nPath, {
      encoding: "utf8",
      flag: "r",
    });

    fs.writeFileSync(
      i18nPath,
      i18nData.replace(/locales: '*.'/, `locales: ['${lng}', '`)
    );

    /* settings.js */

    const settingsPath = path.resolve(workingDir, "src/settings.js");

    if (!fs.existsSync(settingsPath)) {
      return;
    }

    const settingsData = fs.readFileSync(settingsPath, {
      encoding: "utf8",
      flag: "r",
    });

    const data = `{ label: '${lng.toUpperCase()}', value: '${lng.toLowerCase()}', apiValue: '${
      argv.addLanguage
    }' }`;

    const changes = "languages: [";

    fs.writeFileSync(
      settingsPath,
      settingsData.replace(changes, `languages: [\n\t\t${data},`)
    );
  };

  const init = () => {
    if (!argv.addLanguage) return;
    let lng = argv.addLanguage;
    lng = lng.split("-")[0];

    const dest = `public/locales/${lng}`;
    const exists = fs.existsSync(dest);

    try {
      if (exists)
        throw new Error(`${lng.toUpperCase()} has already been added`);
      addLanguage("public/locales/en", `public/locales/${lng}`, lng);
      i18nDocumentUpdate(lng);
    } catch (err) {
      const typedError = err as Error;

      console.log(
        "\n\x1b[31m%s\x1b[0m",
        `${
          typedError.message
            ? typedError.message + "\n"
            : "Something went wrong.\n"
        }`
      );
    }
  };

  init();
};
