const express = require('express');
const path = require('path');
const { WebSocketServer } = require('ws');
const { createServer } = require('http');
const fs = require('fs');

const config = require('./config.json');
let clients = [];

const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });

wss.on('connection', function connection(ws) {
    clients.push(ws);
    ws.on('close', () => {
        clients.pop(ws);
    });
});

// auto refresh on frontend update
let lastUpdateTime = Date.now();
fs.watch('./ejs/', () => {
    const now = Date.now();
    if (now - lastUpdateTime > 50) {
        clients.forEach((ws) => {
            ws.send('update');
        });
    }
    lastUpdateTime = now;
});

app.use(express.json());
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'ejs'));


app.get('/', (req, res) => {
    res.render('home');
});

server.listen(config.port, () => {
    console.log(`Server started on port ${config.port}`);
});