const {
    config_path,
    routes_path,
    init_log_path,
    runtime_log_path
} = require(process.argv[process.argv.length - 1])

const config = require(config_path)
const express = require('express')
const logger = require('./lib/logger')
const routes = require(routes_path)

// loggers
const logger_init = new logger(init_log_path)
const logger_runtime = new logger(runtime_log_path)

const app = express()

// logger
app.use(function(req, res, next) {
    var {url} = req
    logger_runtime.log(url)
    next()
})

// CORS
app.options(function(req, res) {
    //'GET, POST, OPTIONS, PUT, PATCH, DELETE'
    res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS')
    res.end()
})

app.use(function (req, res, next) {
    const {origin} = req.headers
    if (config.cors.includes(origin)) {
        res.setHeader('Access-Control-Allow-Origin', origin)
    }
    res.setHeader('Access-Control-Allow-Credentials', true)
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
    next()
})

//routes
app.use(routes)

// errors handlers
app.use(function(error, req, res, next) {
    // errors
    logger_runtime.error(error)
    res.send(error.message)
    next()
})

app.use(function(req, res, next) {
    res.end()
})

// start listen server
try {
    app.listen(config.port, config.ip)
    logger_init.log(`Listening at http://${config.ip}:${config.port}`)
} catch (e) {
    return logger_init.error(e)
}