'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');

module.exports = class extends Generator {
  initializing() {
    this.repoHash = {
      'custom': 'http://gitlab2.dui88.com/wanghongyuan/customdemo.git',
      'game': 'http://gitlab2.dui88.com/wanghongyuan/gamedemo.git'
    };
  }

  prompting() {
    // Have Yeoman greet the user.
    this.log(
      yosay(`Welcome to the amazing ${chalk.red('generator-dbgame')} generator!`)
    );

    const prompts = [
      {
        type: 'input',
        name: 'projectName',
        message: '输入项目名称',
        default: `${Date.now()}`
      },
      {
        type: 'list',
        name: 'projectType',
        message: '请选择项目类型',
        choices: ['game', 'custom'],
        default: true
      }
    ];

    return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props;
    });
  }

  pull() {
    const done = this.async();
    const Git = require("nodegit");
    const rimraf = require("rimraf");
    const type = this.props['projectType'];
    const projectName = this.props['projectName'];
    const url = this.repoHash[type];
    // Clone a given repository into the `./tmp` folder.
    this.log('正在获取模板.');
    return Git.Clone(url, `./${projectName}`)
      .then(() => {
        rimraf(`./${projectName}/.git`, () => {
          this.log('模板获取完毕.');
          done();
        });
      })
      .catch(function (err) { console.log(err); });
  }

  writing() {
    const fs = require('fs');
    const Handlebars = require('handlebars');
    const sourceURL = this.props['projectName'] + '/source';
    const projectJSONURL = `${sourceURL}/project.json`;
    const content = this.fs.read(projectJSONURL);
    var template = Handlebars.compile(content);
    // this.fs.write(projectJSONURL,template(this.props));
    fs.writeFileSync(projectJSONURL, template(this.props));
    this.log('文件写完毕.');
    this.log('正在安装依赖.');
    this.spawnCommandSync('cnpm', ['install'], { cwd: this.destinationRoot() + '/' + this.props['projectName'] + '/source' })
    this.log('安装依赖完毕.');
    this.log('正在使用vscode打开.');
    this.spawnCommandSync('code', ['.'], { cwd: this.destinationRoot() + '/' + this.props['projectName'] + '/source' })
  }
};
