const express = require('express');
const bodyParser = require('body-parser');
const loginRouter = require('./routers/login');
const menuRouter = require('./routers/mainMenu');
const path = require('path');
const cookieParser = require('cookie-parser');

const checkSession = require('./middlewares/checkSession');

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

function shutdown() {
    console.log('Received kill signal, shutting down gracefully.');
    const serverProcess = app.get('serverProcess');
    if (serverProcess && typeof serverProcess.kill === 'function') {
        console.log('Shutting down server process...');
        serverProcess.kill(); // Send SIGTERM to server process

        serverProcess.on('exit', () => {
            console.log('Server process terminated.');
            process.exit(0); // Exit main process cleanly
        });
    } else {
        console.log('No server process or cannot be killed, exiting.');
        process.exit(0); // Exit main process cleanly
    }
}

const app = express()

app.set('serverProcess', null);

app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'public', 'html')));
app.use('/css', express.static(path.join(__dirname, 'public', 'css')));
app.use('/js', express.static(path.join(__dirname, 'public', 'js')));
app.use('/images', express.static(path.join(__dirname, 'public', 'images')));

app.use(checkSession);

// Mount login and menu routers
app.use('/login', loginRouter);
app.use('/', menuRouter);

// Start the server
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


