package com.xinelu.common.socket;

import java.io.IOException;
import java.util.Map;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ServerEndpoint(value = "/webSocket/{key}")
public class WebSocket {

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam(value = "key") String key, Session session) throws IOException {
        if (StringUtils.isNotBlank(key)) {
            WebSocketUtils.add(key, session);
        } else {
            session.getAsyncRemote().sendText("来自服务器的消息：您未传递key值");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("key") String key) throws IOException {
        WebSocketUtils.remove(key);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session fromSession) {
        if (message.equals("ping")) {
            return;
        }
        for (Map.Entry<String, Session> sessionEntry : WebSocketUtils.clients.entrySet()) {
            // 获取自己
            if (fromSession.getId().equals(sessionEntry.getValue().getId())) {
                //打印消息
                WebSocketUtils.receive(sessionEntry.getKey(), message);
            }
        }

    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        for (Map.Entry<String, Session> sessionEntry : WebSocketUtils.clients.entrySet()) {
            // 获取自己
            if (session.getId().equals(sessionEntry.getValue().getId())) {
                //清除异常连接
                WebSocketUtils.remove(sessionEntry.getKey());
            }
        }
        log.error("发生错误");
        error.printStackTrace();
    }

}
