/**
 * rongxin.gov.rgvn.dashboard.tiandeng
 */

'use strict'

const logFactory = require('./utils/logFactory')
const logUtil = require('./utils/logUtil')
const debug = logFactory(logUtil())('rongxin.gov.rgvn.dashboard.tiandeng')
const express = require('express')
const http = require('http')
const config = require('config')
const env = require('./services/env')
const program = require('commander')

//====================
// program parser
// ====================
program
  .version('1.0.0')
  .usage('[options] ')
  .option('-h, --hostname [hostname]', 'Hostname or IP address for the service to bind, if not presented, use the one specfied in conf file')
  .option('-p, --port [port]', 'The service listening port, if not presented, use the one specified in conf file')
  .option('-l, --log-level [log-level]', 'The service log-level')
  .option('-m, --mode [mode]', 'The service process mode, production, stage or test')
  .parse(process.argv)

let transportConf = {
  host: program.hostname,
  port: program.port
}

const bootstrap = require('nongfu.merchant.bootstrap')
const app = express()
env.setServerMode(app.get('env'))

const router = require('./routes')

app.use('/', router)

bootstrap.init((error, result) => {
  if (error)
    process.exit(1)

  let hostInEnv = process.env.NODE_HOSTNAME
  let portInEnv = process.env.NODE_PORT

  let host = hostInEnv || transportConf.host || config.get('server').host
  let port = portInEnv || transportConf.port || config.get('server').port

  let server = http.createServer(app)

  server.listen(port, host)
  debug.info(`Server start up on listening [host:${host}, port:${port}]`)
})
