package com.its.vds.api.websocket;

import com.its.app.utils.Counter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ItsWebSocketSessionManager {

    private static ItsWebSocketSessionManager _instance = null;

    private volatile boolean serverRun;
    private Counter sessions;
    private ConcurrentHashMap<WebSocketSession, ItsWebSocketSession> sessionMap;

    public static ItsWebSocketSessionManager getInstance() {
        if (_instance == null) {
            synchronized (ItsWebSocketSessionManager.class) {
                if (_instance == null)
                    _instance = new ItsWebSocketSessionManager();
            }
        }
        return _instance;
    }

    private ItsWebSocketSessionManager() {
        this.sessions = new Counter();
        this.sessionMap = new ConcurrentHashMap<>();
    }

    public ConcurrentHashMap<WebSocketSession, ItsWebSocketSession> getMap() {
        return this.sessionMap;
    }

    public int add() {
        return (int) this.sessions.increment();
    }
    public int remove() {
        return (int) this.sessions.decrement();
    }
    public int get() {
        return (int) this.sessions.get();
    }

    public void addSession(WebSocketSession session, ItsWebSocketSession vo) {
        this.sessionMap.put(session, vo);
    }
    public void removeSession(WebSocketSession session) {
        this.sessionMap.remove(session);
    }
    public ItsWebSocketSession getSession(WebSocketSession session) {
        return this.sessionMap.get(session);
    }

    public void reportSession() {
        log.info("Sessions: {}", this.sessionMap.toString());
    }

    public void sendBroadcastMessage(String command, TextMessage message) {
        this.sessionMap.forEach((key, value) -> {
            log.info("{}, {}, {}", command, message, key);
            value.sendMessage(command, message);
        });
    }
}
