#!/usr/bin/env node
'use strict';

/**
 * 代码生成器
 *
 * @author CaiAoLin
 * @date 2018/2/1
 * @version
 */

const path = require('path');
const fs = require('fs');

const command = [];
const params = {};
const rootDir = path.resolve(__dirname, '..');
const appDir = rootDir + '\\app\\';
const controllerDir = appDir + 'controller\\';
const serviceDir = appDir + 'service\\';
const viewDir = appDir + 'view\\';
const templateDir = rootDir + '\\tool\\templates\\';

process.argv.forEach(function(param, index) {
    // 前两个命令忽略 (node 以及当前js目录)
    if (index <= 1) {
        return false;
    }
    if (index === 2) {
        // 记录命令
        command.push(param);
    } else {
        const paramInfo = param.split(':');
        params[paramInfo[0]] = paramInfo.length !== 2 ? '' : paramInfo[1];
    }

});

if (command.length <= 0) {
    console.log('命令错误!');
}

const moduleCommand = command[0];
selectModule(moduleCommand);

/**
 * 模块选择
 *
 * @param {String} moduleCommand - 模块命令
 * @return {void}
 */
function selectModule(moduleCommand) {
    const commandInfo = moduleCommand.split(':');
    if (commandInfo.length !== 2) {
        console.log('命令参数错误');
        return;
    }
    // 读入模板数据
    const templateFile = templateDir + commandInfo[0] + '.txt';
    const templateContent = fs.existsSync(templateFile) ? fs.readFileSync(templateFile) : '';
    switch (commandInfo[0]) {
        case 'controller':
            addFile(commandInfo[1], templateContent, 'controller');
            break;
        case 'service':
            addFile(commandInfo[1], templateContent, 'service');
            break;
        case 'all':
            const controllerContent = fs.readFileSync(templateDir + 'controller.txt');
            const serviceContent = fs.readFileSync(templateDir + 'service.txt');
            const viewContent = fs.readFileSync(templateDir + 'view.txt');
            addFile(commandInfo[1], controllerContent, 'controller');
            addFile(commandInfo[1], serviceContent, 'service');
            addFile(commandInfo[1], viewContent, 'view');
            break;
        default:
            break;
    }
}

/**
 * 新增文件
 *
 * @param {String} name - 文件名
 * @param {String} content - 写入内容
 * @param {String} type - 文件类型
 * @return {void}
 */
function addFile(name, content, type) {
    // 模板变量定义
    const current = new Date();
    const templateData = {
        date: current.getFullYear() + '/' + (current.getMonth() + 1) + '/' + current.getDate(),
    };
    let fileName = '';
    let writeDir = '';
    switch (type) {
        case 'controller':
            fileName = name + '_controller.js';
            // 处理文件大小写
            templateData.name = convertName(name);
            writeDir = controllerDir + fileName;
            break;
        case 'service':
            fileName = name + '.js';
            // 处理文件大小写
            templateData.name = convertName(name);
            templateData.table = params.table === undefined ? name.toLowerCase() : params.table;
            writeDir = serviceDir + fileName;
            break;
        case 'view':
            // 判断是否有对应的文件夹
            const folderName = params.folder === undefined ? name.toLowerCase() : params.folder;
            const folder = viewDir + folderName;
            if (!fs.existsSync(folder)) {
                fs.mkdirSync(folder);
            }
            fileName = name + '.ejs';
            writeDir = folder + '\\' + fileName;
            break;
        default:
            console.log('不支持对应的模块');
            return;
    }
    // 替换模板变量
    content = templateVarReplace(content, templateData);
    // 写入文件
    fs.writeFileSync(writeDir, content);
}

/**
 * 替换模板变量
 *
 * @param {String} content - 模板文件内容
 * @param {Object} templateData - 变量替换内容
 * @return {String} - 返回替换后的内容
 */
function templateVarReplace(content, templateData) {
    content = content.toString();
    if (templateData.name !== undefined) {
        content = content.replace(/{{NAME}}/g, templateData.name);
    }
    if (templateData.date !== undefined) {
        content = content.replace(/{{DATE}}/g, templateData.date);
    }
    if (templateData.table !== undefined) {
        content = content.replace(/{{TABLE}}/g, templateData.table);
    }
    return content;
}

/**
 * 处理文件名(把test_test转换为大驼峰模式TestTest)
 *
 * @param {String} content - 待转换内容
 * @return {String} - 转换后的结果
 */
function convertName(content) {
    let result = '';
    const contentArray = content.split('_');
    for (const tmp of contentArray) {
        result += tmp.substring(0, 1).toUpperCase() + tmp.substring(1);
    }
    return result;
}
