import { default as express } from 'express';
import { default as hbs } from 'hbs';
import * as path from 'path';
import { default as logger }  from 'morgan';
import { default as cookieParser } from 'cookie-parser';
import { default as bodyParser } from 'body-parser';
import * as http from 'http';
import { approotdir } from './approotdir.mjs';
import { normalizePort,
        onError,
        onListening,
        handle404,
        basicErrorHandler
        } from './appsupport.mjs';
import { router as indexRouter } from './routes/index.mjs';
import { router as notasRouter } from './routes/notas.mjs';
import { NotasEnMemoria } from './models/notas-memoria.mjs';
import { default as rfs } from 'rotating-file-stream';

const __dirname = approotdir;

export const app = express();
export const port = normalizePort(process.env.PORT || '3000');
export const server = http.createServer(app);
export const NotasMem = new NotasEnMemoria();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('port', port);

hbs.registerPartials(path.join(__dirname, 'partials'));

app.use(logger(process.env.REQUEST_LOG_FORMAT || 'dev', {
	stream: process.env.REQUEST_LOG_FILE ?
		rfs.createStream(process.env.REQUEST_LOG_FILE, {
			size: '10M',
			interval: '1d',
			compress: 'gzip'
		})
		: process.stdout
	})
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/assets/vendor/bootstrap', express.static(
	path.join(__dirname, 'node_modules', 'bootstrap','dist')));
app.use('/assets/vendor/jquery', express.static(
	path.join(__dirname, 'node_modules', 'jquery', 'dist')));
app.use('/assets/vendor/popper.js', express.static(
	path.join(__dirname, 'node_modules', 'popper.js', 'dist', 'umd')));
app.use('/assets/vendor/feather-icons', express.static(
	path.join(__dirname, 'node_modules', 'feather-icons', 'dist')));
app.use('/', indexRouter);
app.use('/notas', notasRouter);
app.use(handle404);
app.use(basicErrorHandler);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
