/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
const prettier = require('prettier');

const processIcons = require('./lib/process-icons');

const iconComponentPath = path.join(__dirname, '../src/atoms/Icon/Icon.generated.tsx');
const singleIconsPath = path.join(__dirname, '../src/atoms/Icon/icons');
/**

/**
 * Write prettified TS code to a given file
 */
const writeTypeScriptFile = (filename, strings) => {
  const content = strings.join('');
  fs.writeFileSync(
    filename,
    prettier.format(content, {
      trailingComma: 'es5',
      tabWidth: 2,
      singleQuote: true,
      printWidth: 120,
      parser: 'babel',
    })
  );
};

async function run() {
  const icons = await processIcons();
  const header = (extra) =>
    [
      `//\n`,
      `// WARNING\n`,
      `//\n`,
      `// Do not make manual changes to this file.\n`,
      `// This file was generated by scripts/generate-icons.js.\n`,
      `//\n`,
      extra ? `// ${extra}\n` : '',
      `//\n`,
      `\n\n`,
    ].join('');

  writeTypeScriptFile(iconComponentPath, [
    header(),
    `import React from 'react';\n\n`,
    `/**\n`,
    ` * A list of all available icons in the icon set.\n`,
    ` */\n`,
    'export type IconDefinition = ',
    icons.map((i) => `'${i.icon}'`).join(' | '),
    `;\n\n`,
    `export const availableIcons: IconDefinition[] = [`,
    icons.map((i) => `'${i.icon}'`).join(', '),
    `];\n\n`,
    `export const IconSvg = {\n`,
    icons.map((i) => `  '${i.icon}': ${i.innerJsx},\n`).join(''),
    `};\n`,
  ]);

  /**
   *
   * Generate individual components for each icon (for tree shaking)
   *
   */
  // First, delete the old icons to make sure no old icons remain
  const existingIcons = await fs.promises.readdir(singleIconsPath);
  await Promise.all(existingIcons.map((f) => fs.promises.unlink(path.join(singleIconsPath, f))));
  icons.forEach((ico) => {
    writeTypeScriptFile(path.join(singleIconsPath, `${ico.singleComponentName}.tsx`), [
      header(`Generated from: ${ico.filename}`),
      `import React from 'react';\n`,
      `import cs from 'classnames';\n\n`,
      `interface Props {\n`,
      `  style?: React.CSSProperties;\n`,
      `  className?: string;\n`,
      `  title?: string;\n`,
      `}\n\n`,
      `export function ${ico.singleComponentName}(props: Props) {\n`,
      `  return (${ico.outerJsxWithClassNameAndStyle});\n`,
      `};\n`,
    ]);
  });

  writeTypeScriptFile(path.join(singleIconsPath, 'index.tsx'), [
    header(),
    icons.map((i) => `export { ${i.singleComponentName} } from './${i.singleComponentName}';\n`).join(''),
    `\n`,
  ]);
}

run();
