require './tools/console'
fs = require 'fs-extra'
path = require 'path'
child_process = require 'child_process'
readline = require 'readline'

inputCache =
    projectName: 'jne'
    projectVersion: '1.0.0'
    projectPort: 3000

qxfVersion = fs.readFileSync(path.join(__dirname, '../package.json')).toString()
qxfVersion = JSON.parse(qxfVersion).version
rl = null

module.exports = () ->
    rl = readline.createInterface(
        input: process.stdin
        output: process.stdout
        terminal: false
    )

    if process.platform is "win32"
        rl.on("SIGINT", ()->
            process.emit("SIGINT")
        )

    process.on("SIGINT", () ->
        process.exit()
    )

    getProjectName()

getProjectName = () ->
    # rl = createRl()
    rl.question('请输入项目名，该名称将用作监控前缀:', (answer) ->
        if answer.trim() is ''
            console.log '项目名不能为空：'
            rl.close()
            return getProjectName()

        inputCache['projectName'] = answer.trim()
        # rl.close()
        getProjectPort()

    )

getProjectPort = () ->
    # rl = createRl()
    rl.question('请输入web服务端口号，不输默认为3000:', (answer) ->
        inputCache['projectPort'] = answer.trim() or inputCache['projectPort']
        # rl.close()
        getProjectVersion()
    )


getProjectVersion = () ->
    # rl = createRl()
    rl.question('请输入项目版本号，不输默认为1.0.0:', (answer) ->
        inputCache['projectVersion'] = answer.trim() or inputCache['projectVersion']
        # rl.close()
        getQzzProject()
    )

getQzzProject = () ->
    # rl = createRl()
    rl.question('请输入对应的qzz项目名称，如home, flight，没有对应的qzz项目直接回车:', (answer) ->
        inputCache['qzz'] = answer.trim()
        rl.close()
        createFile()
    )

createFile = () ->
    src = path.join(__dirname, '../_template')
    target = process.cwd()

    fs.copy(src, target, (err) ->
        if err
            console.log '初始化失败，错误信息：'
            console.error err
            return

        appPath = path.join(target, 'app.js')
        configPath = path.join(target, 'config.js')
        packagePath = path.join(target, 'package.json')
        pmoPath = path.join(target, 'pom.xml')
        startPath = path.join(target, 'bin/start')

        replaceProject(appPath)
        replaceProject(configPath)
        replaceProject(packagePath)
        replaceProject(pmoPath)
        replaceProject(startPath)

        if inputCache.qzz is ''
            fs.unlinkSync(pmoPath)
        console.green '完成初始化'

        installModules()
    )

installModules = () ->
    console.log '开始安装依赖'
    installCommand = 'npm install --registry=http://registry.npm.corp.qunar.com/'
    child_process.exec(installCommand, (err, stdout, stderr) ->

        console.log stdout

        if err or stderr
            console.red '安装依赖出错，请手动运行' +
                '"npm install --registry=http://registry.npm.corp.qunar.com/"' +
                '完成安装，错误信息:', err or stderr

            process.exit()

        infomation = """
                依赖安装完成

                ====================================Y(^_^)Y========================================
                **** 友情提示：
                **** 1. 执行jne-cli start可以启动本地服务，通过 http://127.0.0.1:#{inputCache.projectPort}访问
                **** 2. 需要创建发布job，可以查看package.json的schema部分，按说明进行修改后执行 jne-cli initschema
                **** 3. 更多使用文档请访问 http://fe.corp.qunar.com
                ===================================================================================


                """
        console.green infomation
        process.exit()
    )

replaceProject = (filePath) ->
    content = fs.readFileSync(filePath).toString()

    content = content.replace(/\$\{projectName\}/g, inputCache.projectName)
            .replace(/\$\{projectVersion\}/g, inputCache.projectVersion)
            .replace(/\${qxfVersion}/g, qxfVersion)
            .replace(/\${qxf_qzzname}/g, inputCache.qzz)
            .replace(/\${port}/g, inputCache.projectPort)

    fs.writeFileSync(filePath, content)
