package com.bonus.tcp.websocket.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bonus.common.core.utils.SpringUtils;
import com.bonus.common.core.utils.StringHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

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


/**
 * 安全带文本socket
 * @author 黑子
 */
@Component
public class AqdSocketHandler implements org.springframework.web.socket.WebSocketHandler {
       private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

//        public SaveDataService service = SpringUtils.getBean(SaveDataService.class);
        private final static Logger LOGGER = LoggerFactory.getLogger(AqdSocketHandler.class);

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            sessions.put(session.getId(),session);
            LOGGER.info("Socket 连接成功，sessionId：{}", session.getId());
        }

        @Override
        public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
            if (message instanceof TextMessage) {
                handlerTextMessage(session, (TextMessage) message);
            } else {
                LOGGER.error(" Socket 消息处理失败，只接受 文本消息，sessionId：{}", session.getId());
            }
        }

        public void handlerTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            final String msg = message.getPayload();
            if (StringHelper.isNotEmpty(msg)) {
                sessions.put(msg,session);
            }
            session.sendMessage(new TextMessage(msg));
            LOGGER.info(" Socket 收到消息：{}", msg);
        }


    public static void sendMessageToUser(String username, String message) {
        WebSocketSession session = sessions.get(username);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                LOGGER.info(" Socket 收到消息：{}", message);
            }
        }
    }
    public static void sendMessageToAll(String message){
        try{
            for (WebSocketSession value : sessions.values()) {
                WebSocketSession session = sessions.get(value.getId());
                if (ObjectUtils.isNotEmpty(session)){
                    session.sendMessage(new TextMessage(message));
                }
            }
        }catch (Exception e){
            LOGGER.info(" Socket 收到消息：{}", message);
        }


    }
        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
            LOGGER.error(" Socket 处理异常，sessionId：{}, 异常原因：{}", session.getId(), exception.getMessage());
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
            LOGGER.info(" Socket 关闭，sessionId：{}", session.getId());
        }


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


}
