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

dotenv.config({path: path.join(process.cwd(), 'configs', '.env')});

const corsOptions = {
    cors: {
        origin: [process.env.PROTOCOL+'://'+process.env.HOST, process.env.PROTOCOL+'://'+process.env.HOST+':4200', process.env.PROTOCOL+'://'+process.env.HOST+':'+process.env.PORT_BACKEND, process.env.PROTOCOL+'://'+process.env.HOST+':'+process.env.PORT_FRONTEND, process.env.PROTOCOL+'://'+process.env.HOST+':'+process.env.PORT_SCLIB],
        methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
        credentials: true
    }
};

const express = require('express');
const backend = express();
const backendServer = require('http').createServer(backend);
const io = require('socket.io')(backendServer, corsOptions);
const frontend = express();
const frontendServer = require('http').createServer(frontend);
const morgan = require('morgan');
const log = require('loglevel');
const chalk = require('chalk');
const prefix = require('loglevel-plugin-prefix');

prefix.reg(log);
prefix.apply(log, {template: '[%t]', timestampFormatter: (date) => `${chalk.gray(date.toISOString())}`});

if (process.env.NODE_ENV !== 'production') {
    backend.use(morgan(`[${chalk.gray(`:date[iso]`)}] :url :method ${chalk.gray(`:status`)} :response-time ms`, {skip: (req, res) => { return req.method == 'OPTIONS' }}));
    log.setDefaultLevel('info');
} else {
    log.setDefaultLevel('error');
}

// start servers
(async function () {
    log.info('Backend started for client %s%s %s', chalk.greenBright(process.env.CLIENT_NAME), (process.env.POS_MULTI_TENANT_ENV) ? ' '+chalk.blueBright(process.env.POS_MULTI_TENANT_ENV) : '', (process.env.POS_DEVELOPMENT_MODE == 'true') ? 'in '+chalk.greenBright('development')+' mode' : '');
    // socket connection
    global.io = io;
    // loaders
    await require('./loaders')(backend, corsOptions, frontend);
    // servers listen
    try {
        backendServer.listen(backend.get('port'), backend.get('host'), () => { });
        frontendServer.listen(frontend.get('port'), frontend.get('host'), () => { });
    } catch (err) {
        log.error(err);
    }
})();

module.exports = {
    backend,
    frontend
};
