const args = process.argv;
const path = require('path');
const fs = require('fs');

const shell = require('shelljs');
const readThemeRegistry = require('./lib/ReadThemeRegistry');

let theme = args[2];
if (!theme) {
  shell.echo('❌ Please enter a theme name');
}

if (!theme.toLowerCase().endsWith('theme')) {
  theme = theme + 'Theme';
}

const themeId = theme.replace(/\s+/, '');


const dir = path.resolve(__dirname, '../src/UI/Theme/', themeId);
if (fs.existsSync(dir)) {
  shell.echo('❌ Theme `' + theme + '` already exists');
  process.exit(0);
}

// Create Theme Folder
fs.mkdirSync(dir);
shell.echo('✅ Created Folder', dir);

// Create Style Library
fs.writeFileSync(
  path.resolve(dir, 'theme.json'),
  fs.readFileSync(path.resolve(__dirname, './theme-templates/theme.json')).toString(),
);
shell.echo('✅ Created theme.json');

// Create Theme Object
fs.writeFileSync(
  path.resolve(dir, 'index.js'),
  fs.readFileSync(path.resolve(__dirname, './theme-templates/index.js')).toString().replace(/\$THEME_ID/g, themeId),
);
shell.echo('✅ Created index.js');

// Re-write ThemeRegistry
const registry = readThemeRegistry()
  .concat({
    id: themeId,
    name: theme,
  });

const imports =
  registry.map(it => `import ${it.id} from './${it.id}';`).join('\n');

const themes =
  registry.map(it => `    ['${it.name}']: ${it.id},`).join('\n');

const disclaimer = '// This file is generated by create-new-theme.js script';

fs.writeFileSync(
  path.resolve(dir, '../ThemeRegistry.js'),
  disclaimer + '\n' + imports + '\n\n/*eslint no-useless-computed-key: "off"*/\nexport const themes = {\n' + themes + '\n};',
);
shell.echo('✅ Updated ThemeRegistry.js');

// Recompile Style Resources
const output = shell.exec(`node scripts/build-theme-resources.js`);
if (output.code !== 0) {
  shell.echo(
    '❌ Unable to build the theme resources. Error is:',
  );
  shell.echo(output.stdout);
  shell.echo(output.stderr);
  shell.exit(output.code);
}

shell.echo('✅ Themes resources built');
