import 'babel-polyfill';
import {existsSync, mkdirSync} from 'fs';
import {join} from 'path';
import {prompt} from 'inquirer';
import rimraf from 'rimraf';
import {green, red} from 'chalk';
import {downloadFromUrl, unzip, startProcess, writePackageJsonSync} from '../utils';

export default function(program) {
  program
    .command('theme [name]')
    .alias('t')
    .description('Generates a new theme directory containing Slate\'s theme boilerplate.')
    .action(async (name) => {
      let dirName = name;

      if (!dirName) {
        const answers = await prompt({
          type: 'input',
          name: 'dirName',
          message: 'Please enter a directory name for your theme (a new folder will be created):',
          default: 'theme',
          validate: (value) => {
            const validateName = value.match(/^[\w^'@{}[\],$=!#().%+~\- ]+$/);

            if (validateName) {
              return true;
            }

            return 'A directory name is required.';
          },
        });

        dirName = answers.dirName;
      }

      const workingDirectory = process.cwd();
      const s3Url = 'https://sdks.shopifycdn.com/slate/latest/slate-src.zip';
      const root = join(workingDirectory, dirName);

      if (existsSync(root)) {
        console.log('');
        console.error(red(`  ${root} is not an empty directory`));
        console.log('');
        return null;
      }

      console.log('');
      console.log('  This may take some time...');
      console.log('');

      mkdirSync(root);

      return downloadFromUrl(s3Url, join(root, 'slate-theme.zip'))
        .then((themeZipFile) => {
          return unzip(themeZipFile, root);
        })
        .then(() => {
          console.log(`  ${green('✓')} slate-theme download completed`);

          const pkg = join(root, 'package.json');

          writePackageJsonSync(pkg, dirName);

          return startProcess('npm', ['install', '@shopify/slate-tools', '--save-dev', '--save-exact'], {
            cwd: root,
          });
        })
        .then(() => {
          console.log(`  ${green('✓')} devDependencies installed`);
          console.log(`  ${green('✓')} ${dirName} theme is ready`);
          console.log('');

          return null;
        })
        .catch((err) => {
          console.error(red(`  ${err}`));

          rimraf(root, () => {
            console.log('');
            console.log('  Cleaned up theme');
            console.log('');
          });
        });
    });
}

@@ -183,16 +183,47 @@
 chalk';%0A
+import figures from 'figures';%0A
 import %7B
@@ -1347,16 +1347,33 @@
 r(red(%60 
+ $%7Bfigures.cross%7D
  $%7Broot%7D
@@ -1403,16 +1403,16 @@
 ory%60));%0A
-
         
@@ -1791,19 +1791,28 @@
 $%7Bgreen(
-'%E2%9C%93'
+figures.tick
 )%7D slate
@@ -2148,19 +2148,28 @@
 $%7Bgreen(
-'%E2%9C%93'
+figures.tick
 )%7D devDe
@@ -2229,11 +2229,20 @@
 een(
-'%E2%9C%93'
+figures.tick
 )%7D $

use figrues instead of hardcoded ticks