co = require('co')

log = require('./log')
log.system.info '\n\n\n\n\nStarting...\n'

mongoStore = require('./mongoStore')
sqlStore = require('./sqlStore')
webServer = require('./webServer')

#========== 处理关闭 ==========#
gStopAllOthers = ->
    try
        log.system.info '=== Web Server Closed'

        yield from mongoStore.gDispose()
        yield from sqlStore.gEnd()

        log.system.info '===== !!! SYSTEM DOWN !!! ========================='
    catch e
        log.system.error e, "gStopAllOthers"
# 关闭系统
# 先让服务器停止，停止接收请求，再停数据库等
closeSystem = ->
    log.system.info "!!!ASKED TO STOP!!!"
    webServer.server.destroy()

process.on 'SIGINT', closeSystem
process.on 'SIGTERM', closeSystem

#========== 处理启动 ==========#

webServer.server.on 'close', ->
    # 先等待服务器关闭，再关闭Mongo等
    co(gStopAllOthers)

# 服务器启动前的准备
start = ->
    # yield from require('./mongoIndexes').ensureIndexes()

    log.system.info 'All components started!'
    # 开始监听
    yield from webServer.start()
    log.system.info '===== !!! SYSTEM UP !!! ========================='
    console.log '===== !!! SYSTEM UP !!! ========================='


co(start).catch (e) -> log.system.error(e)





