'use strict';

const { join, dirname } = require('path');
const { readFileSync, writeFileSync, mkdirSync, existsSync } = require('fs');
const config = require('../config');
const srcDir = join(__dirname, '../../src');
const ENCODING = 'utf-8';

Object.keys(config).forEach(theme => {
  try {
    const { pkg } = config[theme];
    const themeDir = dirname(require.resolve(pkg));
    const targetDir = join(srcDir, '_themes');

    if (!existsSync(targetDir)) {
      mkdirSync(targetDir);
    }

    const convertMap = new Map();
    convertMap.set('variables.scss2css.scss', `variables.${theme}.var.scss`);
    convertMap.set('variables.scss', `variables.${theme}.scss`);
    convertMap.set('icons.scss', `icons.${theme}.scss`);
    convertMap.set('index-noreset.scss', `index-noreset.${theme}.scss`);
    convertMap.set('index.scss', `index.${theme}.scss`);
    convertMap.set('variables.css', `variables.${theme}.css`);
    convertMap.set('dist/next-noreset.var.css', `next-noreset.${theme}.var.css`);
    convertMap.set('dist/next.var.css', `next.${theme}.var.css`);
    convertMap.set('design-token.js', `design-token.${theme}.js`);

    for (const [ sourceFile, targetFile ] of convertMap.entries()) {
      const sourceFilePath = join(themeDir, sourceFile);
      const targetFilePath = join(targetDir, targetFile);
      let sourceContent = readFileSync(sourceFilePath, { encoding: ENCODING });
      if (sourceFile === 'icons.scss' || sourceFile === 'index-noreset.scss' || sourceFile === 'index.scss') {
        sourceContent = sourceContent.replace('variables.scss', `variables.${theme}.scss`).replace('icons.scss', `icons.${theme}.scss`);
      }
      writeFileSync(targetFilePath, sourceContent, { encoding: ENCODING });
      console.log(`write ${sourceFile} to ${targetFile} done.`);
    }
  } catch (e) {
    console.error(`ignore ${theme} post install, reason: ${e.message}`);
  }
});
