'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('design-token.js', `design-token.${theme}.js`);

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