package com.hdkj.lt.core.ws.handler;

import com.alibaba.fastjson.JSON;
import com.hdkj.lt.core.ws.config.WebSocketConfiguration;
import com.hdkj.lt.core.ws.model.WebSocketMessageEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2024/04/26 10:57
 * @Version: 1.0
 */
@Slf4j
public abstract class AbstractDefaultWebSocketHandler implements WebSocketHandler {

    public static ConcurrentHashMap<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();

    public abstract String getPath();

    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) throws Exception {
        Map<String, Object> attributes = session.getAttributes();
        Object sessionKey = attributes.get(WebSocketConfiguration.SESSION_KEY);
        SESSIONS.put(String.valueOf(sessionKey), session);
        log.info("connect successful, sessionKey: {}, sessionId: {}", sessionKey, session.getId());
    }

    @Override
    public void handleMessage(@NonNull WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        Object payload = message.getPayload();
        log.info("payload: {}", payload);
    }

    @Override
    public void handleTransportError(@NonNull WebSocketSession session, Throwable throwable) throws Exception {
        log.error("connect error：{}", throwable.getMessage());
        throwable.printStackTrace();
    }

    @Override
    public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull CloseStatus closeStatus) throws Exception {
        log.info("closed connect，sessionId: {}", session.getId());
        SESSIONS.remove(session.getId());
        session.close(closeStatus);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 发送信息到指定的session请求域中
     *
     * @param sessionKey    会话key
     * @param messageEntity 消息体
     */
    public <T extends WebSocketMessageEntity> void sendMessage(String sessionKey, T messageEntity) throws IOException {
        log.info("send message: {}", messageEntity);
        WebSocketSession session = SESSIONS.get(sessionKey);
        if (Objects.nonNull(session)) {
            synchronized (session) {
                session.sendMessage(new TextMessage(JSON.toJSONString(messageEntity)));
            }
        }
    }

}
