const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 4000 });

let connections = 0;

wss.on('connection', ws => {
    connections++;
    broadcastConnections();
    console.log('クライアント接続 - 現在の接続数:', connections);

    ws.on('close', () => {
        connections--;
        broadcastConnections();
        console.log('クライアント切断 - 現在の接続数:', connections);
    });

    ws.on('message', message => {
        try {
            const data = JSON.parse(message);
            if (data.type === "userName") {
                console.log(`${data.name}さんが入室!`);
            } else if (data.type === "ghostPosition") {
                // ユーザー名付きでログ出力
                console.log(` ${data.name} のGhostモデル位置: x=${data.x} y=${data.y} z=${data.z}`);
                broadcast(JSON.stringify({
                    type: "ghostPositionBroadcast",
                    name: data.name,
                    x: data.x,
                    y: data.y,
                    z: data.z,
                    timestamp: data.timestamp
                }));
            }
        } catch (err) {
            console.error("JSONパースエラー:", err);
        }
    });
});

function broadcast(data) {
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
}

function broadcastConnections() {
    broadcast(JSON.stringify({
        type: "connectionsBroadcast",
        connections: connections
    }));
}