/**
 * Created by chumahtung on 2016/11/15.
 */

var readlineSync = require('@fsteam/readline-sync');
var iconv = require('iconv-lite');
var copyDir = require('copy-dir');
var fs = require('fs');
var path = require('path');
var hoo = require('../');
var _ = require('./util');
var settings = require('../conf/settings');
readlineSync.setDefaultOptions({prompt: '$ '});
var date = new Date();
var today = date.getFullYear().toString() + ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()).toString();
var author = settings.author || 'chumahtung';
var copyPath = '';

// question方法
var types = ['pc端活动(新)', 'pc端活动(旧)', '移动端活动', '拷贝其他活动专题', '游戏官网', '拷贝其他官网项目'];

var availableTemplates = [{
  path: 'platform/20161028',
  name: '双十一平台活动',
  desc: '九宫格抽奖类型',
  url: 'http://huodong.37.com/dist/platform/20161028/'
}, {
  path: 'liezhan/20161012',
  name: '烈斩公测媒体专题',
  desc: '媒体活动专题，带抽奖和卡牌切换',
  url: 'http://huodong.37.com/dist/platform/20161028/'
}];

var templatesForSelect = _.map(availableTemplates, function (item) {
  return item.name + '----' + item.desc;
}).concat(['自定义']);

var type = readlineSync.keyInSelect(types, "请选择类型：");

if (type === -1) {
  return;
}

if (type === 3) {
  var selectedCopy = readlineSync.keyInSelect(templatesForSelect, "请选择模板：");
  if (selectedCopy === -1) return;
  if (selectedCopy === (templatesForSelect.length - 1)) {
    while(true){
      copyPath = readlineSync.question('请输入被拷贝的活动路径（必填）:', {
        limit: function (input) {
          if (!input) return false;
          if (/^[a-z]{2,}\/[0-9a-z]{4,}$/.test(input)) return true;
          return false;
        },
        limitMessage: '抱歉, 格式错误（必填）.'
      });

      if(fs.existsSync(path.join(process.cwd(),settings.sourceDir,copyPath))){
        break;
      }else{
        process.stdout.write(path.join(process.cwd(),settings.sourceDir,copyPath)+'---路径不存在，请重新输入!\n');
      }
    }

  } else {
    copyPath = availableTemplates[selectedCopy].path;
  }
}

if (type === 4 || type === 5) {
  hoo.log.info('hoo官网工程化仍在处理中，敬请期待！');
  return;
}

var gameKey = readlineSync.question('请输入游戏gamekey（必填）:', {
  limit: function (input) {
    if (!input) return false;
    if (!/^[a-z]{2,}$/.test(input)) return false;
    return true;
  },
  limitMessage: '抱歉, gamekey格式不正确（只能出现小写字母）.'
});

var uniqueId = readlineSync.question('请输入活动唯一标识（默认' + gameKey + '/' + today + '）:', {
  limit: function (input) {
    if (!/^[0-9a-z]{4,}$/.test(input))return false;
    return true;
  },
  limitMessage: '抱歉, ' + gameKey + '\/$<lastInput> 不是合法的格式.',
  defaultInput: today
});

uniqueId = gameKey + '\/' + uniqueId;

if(!readlineSync.keyInYNStrict('将会创建'+uniqueId+'目录，确定继续？')){
  return;
};

if(type !== 3){
  var game_name = readlineSync.question('请输入游戏名称（必填）:', {
    limit: function (input) {
      if (!input) return false;
      return true;
    },
    limitMessage: '抱歉, 游戏名称不能为空.'
  });

  var title = readlineSync.question('请输入活动标题（T）:', {
    limit: function (input) {
      if (!input) return false;
      return true;
    },
    limitMessage: '抱歉, 活动标题不能为空.'
  });

  var desc = readlineSync.question('请输入活动描述（D，不低于10个字）:', {
    limit: function (input) {
      if (!input) return false;
      if (input.length < 10) return false;
      return true;
    },
    limitMessage: '抱歉, 活动描述不得低于10个字.'
  });

  var keywords = readlineSync.question('请输入活动关键字（K）:', {
    limit: function (input) {
      if (!input) return false;
      return true;
    },
    limitMessage: '抱歉, 关键字不能为空.'
  });

}

/*var MAX = 100, MIN = 0, value = 0, key;

 while (true) {
 hoo.log.info('\x1B[1A\x1B[K|' +
 (new Array(value + 1)).join('-') + 'O' +
 (new Array(MAX - value + 1)).join('-') + '| ' + value);
 key = readlineSync.keyIn('',
 {hideEchoBack: true, mask: '', limit: 'zx '});
 if (key === 'z') { if (value > MIN) { value--; } }
 else if (key === 'x') { if (value < MAX) { value++; } }
 else { break; }
 }*/

var data = {
  game_name: game_name,
  title: title,
  desc: desc,
  author: author,
  keywords: keywords
};

var source_path = uniqueId;
var _ = require('underscore');
var xtpl = require('xtpl');
var mkdirp = require('mkdirp');

var templateDirs = ['pc/new', 'pc/old', 'mobile'].concat([copyPath]).concat(['gamesite', 'gamesite']);
var dest_path = path.join(process.cwd(), settings.sourceDir, source_path);
var prePromise = Promise.resolve();

prePromise = prePromise.then(function () {
  if (!fs.existsSync(dest_path)) {
    mkdirp.sync(dest_path);
  }

  return new Promise(function (resolve) {
    if (type === 3) {
      resolve();
    } else {
      xtpl.renderFile(path.join(__dirname, '../template', templateDirs[type], 'index.html'), data, function (error, content) {
        fs.writeFile(dest_path + '/index.html', content, function (err) {
          if (err) throw err;
          hoo.log.info('index.html创建完成');
          resolve();
        });
      });
    }
  });
});

prePromise = prePromise.then(function () {
  return new Promise(function (resolve) {
    copyDir.sync(type === 3 ? path.join(process.cwd(), settings.sourceDir, templateDirs[type]) : path.join(__dirname, '../template', templateDirs[type]), dest_path, function (stat, filepath, filename) {
      if (stat === 'directory' && (filename === '.svn' || filename === '.git' || filename === '.hoo_cache')) {
        return false;
      }
      if (type !== 3 && filename === 'index.html') {
        return false;
      }
      return true;
    }, function (err) {
      hoo.log.info(err);
    });
    hoo.log.info('dir copied');
    resolve();
  })
});

prePromise.then(function () {
  hoo.log.info('finished');
});
