#!/usr/bin/env node

/**
 * Module dependencies.
 */

const app = require('server/app');
const debug = require('debug')('server:server');
const http = require('http');
const mongoose = require('mongoose');
const cron = require('node-cron');

const { refreshQuestions, refreshUsers } = require('server/utils/cronRefresh');

require('dotenv').config();

/**
 * Get port from environment and store in Express.
 */

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

mongoose.connect(process.env.DB_CONN_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    dbName: process.env.DB_NAME,
});

mongoose.connection.once('open', () => console.log('[INFO]: MongoDB connected'));
mongoose.connection.on(
    'error',
    console.error.bind(console, '[ERROR]: MongoDB connection error - ')
);

// cron.schedule('*/30 * * * * *', refreshQuestions);
// cron.schedule('*/2 * * * *', refreshUsers);

server.listen(port, console.log(`Listening on port: ${port}`));
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
    return parseInt(val, 10) || val;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
        default:
            throw error;
    }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
    const addr = server.address();
    const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    debug('Listening on ' + bind);
}
