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) {
        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;
        console.log(`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');
}
