const express = require('express');
const path = require('path');
const { fork } = require('child_process');
const httpStatus = require('../helpers/status_codes');

const router = express.Router();
const backendPath = path.join(__dirname, '..', '..', 'backend');

router.get('/', (req, res) => {
    res.sendFile('main_menu.html', {root: path.join(__dirname, '..', 'public', 'html')});
});

router.post('/server', async (req, res) => {
    const action = req.body.action;
    let serverProcess = req.app.get('serverProcess');

    if (action === 'start') {
        if (serverProcess) {
            return res.status(httpStatus.BAD_REQUEST).send({message: 'Server is already running.'});
        }
        const serverPath = path.join(backendPath, 'src', 'app.js');
        serverProcess = fork(serverPath, [], { stdio: 'inherit' }); // Add stdio: 'inherit' to see child process logs in the parent process console

        serverProcess.on('message', (msg) => {
            console.log('Message from server:', msg);
        });

        serverProcess.on('close', (code, signal) => {
            console.log(`Server process exited with code ${code} and signal ${signal}`);
            req.app.set('serverProcess', null);
        });

        req.app.set('serverProcess', serverProcess); // Update the serverProcess in the app
        res.status(httpStatus.OK).json({message: 'Server starting...'});
    } else if (action === 'stop') {
        if (!serverProcess) {
            return res.status(httpStatus.BAD_REQUEST).json({message: 'Server is not running.'});
        }
        serverProcess.kill('SIGTERM');
        res.status(httpStatus.OK).json({message: 'Server stopping...'});
    } else {
        res.status(httpStatus.BAD_REQUEST).json({message: 'Invalid action.'});
    }
});

module.exports = router;
