'use strict';
/*
 * Build javascript passthrough modules for highlight.js languages
 */
const path = require('path');
const fs = require('fs');
const camel = require('to-camel-case');
const autogenMessage =
  '//\n// This file has been auto-generated by the `npm run build-languages-prism` task\n//\n\n';

function makeImportName(name) {
  if (name === '1c') {
    return 'oneC';
  }
  if (name === 'false') {
    return 'falselang';
  }
  return camel(name);
}

function createLanguagePassthroughModule(file) {
  const importName = makeImportName(file.split('.js')[0]);
  const lines = [
    `import ${importName} from "refractor/lang/${file}";`,
    `export default ${importName}`,
    ''
  ];

  fs.writeFile(
    path.join(__dirname, `../src/languages/prism/${file}`),
    lines.join(';\n'),
    err => {
      if (err) {
        process.exit(1);
      }
    }
  );
}

function createAsyncLanguageLoaderLine(file) {
  const fileWithoutJS = file.split('.js')[0];
  const importName = makeImportName(fileWithoutJS);

  return `  ${importName}: createLanguageAsyncLoader("${importName}", () => import(/* webpackChunkName: "react-syntax-highlighter_languages_refractor_${importName}" */ "refractor/lang/${file}")),`;
}

function createSupportedLanguagesArray(files) {
  let lines = [autogenMessage, `export default [`];
  lines = lines.concat(files.map(file => `\n  '${file.split('.js')[0]}',`));
  lines.push(`\n];\n`);

  fs.writeFile(
    path.join(__dirname, `../src/languages/prism/supported-languages.js`),
    lines.join(''),
    err => {
      if (err) {
        throw err;
      }
    }
  );
}

function createAsyncLanguageLoadersIndex(files) {
  let lines = [
    `import createLanguageAsyncLoader from "./create-language-async-loader"`,
    `export default {`
  ];

  lines = lines.concat(files.map(file => createAsyncLanguageLoaderLine(file)));
  lines.push(`}`);

  fs.writeFile(
    path.join(__dirname, `../src/async-languages/prism.js`),
    lines.join('\n'),
    err => {
      if (err) {
        throw err;
      }
    }
  );
}

fs.readdir(
  path.join(__dirname, '../node_modules/refractor/lang'),
  (err, files) => {
    console.log(files);
    if (err) {
      process.exit(1);
    }
    files.forEach(createLanguagePassthroughModule);

    createAsyncLanguageLoadersIndex(files);
    createSupportedLanguagesArray(files);

    const availableLanguageNames = files.map(file => file.split('.js')[0]);
    console.log(availableLanguageNames.join('\n'));
    const languagesLi = availableLanguageNames.map(
      name =>
        `\n* ${makeImportName(name)}${
          makeImportName(name) !== name ? ` (${name})` : ''
        }`
    );
    const languageMD = `## Available \`language\` imports ${languagesLi.join(
      ''
    )}`;
    fs.writeFile(
      path.join(__dirname, '../AVAILABLE_LANGUAGES_PRISM.MD'),
      languageMD,
      err => {
        if (err) {
          process.exit(1);
        }
      }
    );

    const defaultExports = availableLanguageNames.map(
      name =>
        `export { default as ${makeImportName(name)} } from './${name}';\n`
    );
    fs.writeFile(
      path.join(__dirname, '../src/languages/prism/index.js'),
      defaultExports.join(''),
      err => {
        if (err) {
          process.exit(1);
        }
      }
    );
  }
);
