import {promises as fsp} from 'fs';
import {join} from 'path';
import nunjucks from 'nunjucks';
import {generateLove, LoveVariant} from './love';

export async function entry(): Promise<void> {
  const themesDirectory: string = join(__dirname, '../vscode/themes/');
  // Configure Nunjucks to use the templates for `source/vscode/themes/`.
  nunjucks.configure(themesDirectory, {
    lstripBlocks: true,
    trimBlocks: true,
    throwOnUndefined: true
  });

  const love: LoveVariant[] = generateLove();
  for (const variant of love) {
    const template: string = await fsp.readFile(
      join(themesDirectory, 'love-template.color-theme.json'),
      'utf8'
    );

    const outputPath: string = join(
      themesDirectory,
      `love-${variant.name}.color-theme.json`
    );

    const output: string = nunjucks.renderString(template, {
      love: variant
    });
    let formattedOutput = '';
    for (const line of output.split('\n')) {
      // Don't include the line in the output if it's a comment (starts with '//').
      if (/^\s+\/\/.+$/.exec(line)) {
        continue;
      }

      formattedOutput += line;
      formattedOutput += '\n';
    }

    let outputObject: object;
    try {
      outputObject = JSON.parse(formattedOutput);
    } catch (error) {
      console.log('Could not parse formatted output as regular JSON:');
      console.log(error.message);
      return;
    }

    await fsp.writeFile(outputPath, JSON.stringify(outputObject));
  }
}

if (require.main === module) {
  entry();
}
