import { default as DBG } from 'debug';
const debug = DBG('notas:debug'); 
const dbgerror = DBG('notas:error');

import * as util from 'util';
import { port } from './app.mjs';
import { server } from './app.mjs';

export function normalizePort(val) {
        const puerto = parseInt(val, 10);
        if (isNaN(puerto)) {
                return val;
        }
        if (puerto >= 0) {
                return puerto;
        }
        return false;
}

export function onError(error) {
	dbgerror(error);
        if (error.syscall != 'listen') {
                throw error;
        }
        const unir = typeof port === 'string'
                        ? 'Pipe ' + port
                        : 'Port ' + port;
        switch(error.code) {
                case 'EACCES':
                        console.error(`${unir} necesita mas privilegios`);
                        process.exit(1);
                        break;
                case 'EADORINUSE':
                        console.error(`${unir} esta en uso`);
                        process.exit(1);
                        break;
                default:
                        throw error;
        }
}

export function onListening() {
        const direccion = server.address();
        const unir = typeof direccion === 'string'
		? 'pipe ' + direccion
		: 'port ' + direccion.port;
        debug(`Escuchando en ${unir}`);
}

export function handle404(req, res, next) {
        const err = new Error('No encontrado');
        err.status = 404;
        next(err);
}

export function basicErrorHandler(err, req, res, next) {
        if (res.headerSent) {
                return next(err);
        }

        res.locals.message = err.message;
        res.locals.error = req.app.get('env') === 'development'
                                ? err : {};

        res.status(err.status || 500);
        res.render('error');
}

process.on('uncaughtException', function(err) {
	console.error(`Me mori!!! - ${(err.stack || err)}`);
});

process.on('unhandledRejection', (reason, p) => {
	console.error(`Rechazo sin manejar en: ${util.inspect(p)} razon: ${reason}`);
});
