const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const path = require('path');

// Menyediakan akses ke seluruh file HTML/JS/CSS di folder ini
app.use(express.static(__dirname));

// Memori Utama Antrian di Server
let state = {
    tickets: [],
    counters: { 1: null, 2: null, 3: null, 4: null, 5: null, 6: null, 7: null, 8: null, 9: null, 10: null, 11: null },
    activeCall: null,
    settings: {
        runningText: "Selamat Datang di Penerimaan Peserta Didik Baru (PPDB) SMAN 01 Pemalang."
    }
};

io.on('connection', (socket) => {
    // Saat ada laptop/TV yang membuka browser, kirimkan data antrian terakhir
    socket.emit('stateUpdate', state);

    // Saat ada loket/kiosk yang melakukan aksi (ambil antrian / panggil)
    socket.on('updateState', (newState) => {
        state = newState;
        // Broadcast (siarkan) pembaruan ke semua laptop secara instan!
        io.emit('stateUpdate', state);
    });
});

const PORT = 3000;
http.listen(PORT, '0.0.0.0', () => {
    console.log(`\n==============================================`);
    console.log(` SERVER ANTRIAN SMAN 1 PEMALANG AKTIF`);
    console.log(`==============================================`);
    console.log(`Buka aplikasi di komputer ini: http://localhost:${PORT}`);
    
    // Tampilkan IP jaringan lokal agar komputer lain bisa mengaksesnya
    const { networkInterfaces } = require('os');
    const nets = networkInterfaces();
    for (const name of Object.keys(nets)) {
        for (const net of nets[name]) {
            if (net.family === 'IPv4' && !net.internal) {
                console.log(`Buka aplikasi dari LAPTOP LAIN: http://${net.address}:${PORT}`);
            }
        }
    }
    console.log(`==============================================\n`);
});
