const fs = require('fs');

const themes = ['blue', 'blue-red', 'dark', 'orange', 'violet'];
const themesPath = 'themes/';

const lineDelimiter = '\n';
const linePrefix = '    ';
const variablesFlag = '/* variables */';
const allThemesMapKeys = [];
const variableStart = '$m: map-merge($m, (';


themes.forEach(themeName => {
  const themeFile = `${themesPath}_${themeName}.sass`;
  const themeFileContent = fs.readFileSync(themeFile).toString();
  const fileByLines = themeFileContent.split(lineDelimiter);
  fileByLines
    .filter(line => line.startsWith(variableStart))
    .map(line => line.substr(0, line.indexOf(':', variableStart.length)).substr(variableStart.length))
    .forEach(variableName => {
      if (!allThemesMapKeys.includes(variableName)) {
        allThemesMapKeys.push(variableName);
      }
    });
});

console.log('-----------');
console.log('\x1b[36m%s\x1b[0m', ` $${allThemesMapKeys.join(', $')} (${allThemesMapKeys.length})`);
console.log('-----------');

const builderFileSource = `${themesPath}_theme-builder.sass`;
const builderFile = fs.readFileSync(builderFileSource).toString();
const variablesStrings = allThemesMapKeys.map(x => `${linePrefix}$${x}: map-get($map, '${x}')`).join(lineDelimiter);

const builderFileParts = builderFile.split(variablesFlag);
if (builderFileParts.length === 3) {
  builderFileParts[1] = `${lineDelimiter}${lineDelimiter}${variablesStrings}${lineDelimiter}${lineDelimiter}${linePrefix}`;
  const newBuilderFile = builderFileParts.join(variablesFlag);
  fs.writeFile(builderFileSource, newBuilderFile, (error) => {
    if (error) {throw error;}
    console.log(`${builderFileSource} updated`);
  });
}
