package com.its.op.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/ws/messages.do")
public class ItsWebSocketHandler extends TextWebSocketHandler {

    public ItsWebSocketHandler() {

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            for (Map.Entry<org.springframework.web.socket.WebSocketSession, ItsWebSocketSession> obj : ItsWebSocketSessionManager.getInstance().getMap().entrySet()) {
                if (obj.getValue() != null) {
                }
            }
        }));

        log.info("WebsocketHandler() START");
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 클라이언트가 연결되었을때 실행
        log.info("afterConnectionEstablished: " + session.getRemoteAddress() + ",  URI: " + session.getUri() + ", UUID: " + session.getId());
        super.afterConnectionEstablished(session);

        ItsWebSocketSession vo = new ItsWebSocketSession(this, session);
        ItsWebSocketSessionManager.getInstance().addSession(session, vo);
    }

    //클라이언트가 웹소켓 서버로 메시지를 전송했을 때 실행
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("handleTextMessage: " + session.getRemoteAddress() + ",  Uri[" + session.getUri() + "], UUID[" + session.getId() + "], message[" + message.getPayload() + "]");
        /*List<String> requests = ItsUtils.split(message.getPayload(), ":");
        if (requests.size() != 2) {
            log.error("Request data parsing error: {}", requests);
            session.close();
            return;
        }
*/
        ItsWebSocketSession sessionClient = ItsWebSocketSessionManager.getInstance().getSession(session);
        if (sessionClient == null) {
            log.error("Request session not found: {}", session);
            session.close();
            return;
        }
        log.info("Payload: {}", message.getPayload());
    }

    //클라이언트 연결을 끊었을 때 실행
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("afterConnectionClosed: " + session.getRemoteAddress() + ",  URI: " + session.getUri() + ", UUID: " + session.getId());
        ItsWebSocketSessionManager.getInstance().removeSession(session);
        super.afterConnectionClosed(session, status);
    }

}
