const express = require('express');
const path = require('path');
const fs = require('fs').promises;
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');
    const configFilePath = path.join(backendPath, 'config', 'config.json');

    try {
        await fs.access(configFilePath);
    } catch (error) {
        if(action === 'start'){
            return res.status(httpStatus.BAD_REQUEST).send({ message: 'Config file is missing, cannot start server.' });
        }
    }

    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);

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

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

        req.app.set('serverProcess', serverProcess); // Update the serverProcess in 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();
        req.app.set('serverProcess', null);
        res.status(httpStatus.OK).json({message: 'Server stopping...'});
    } else {
        res.status(httpStatus.BAD_REQUEST).json({message: 'Invalid action.'});
    }
});

module.exports = router;
