package com.zjty.autotest.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import static com.zjty.autotest.websocket.WebSocketCache.webSocketMap;

/**
 * @author C
 */
@SuppressWarnings("SpringAutowiredFieldsWarningInspection")
@ServerEndpoint("/imserver/{id}")
@Component
@Slf4j
public class WebSocketServer {
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        webSocketMap.put(id, session);
        log.info("建立连接:" + id);
        this.sendMessage(id, "连接成功");
        log.info("当前连接Map:" + webSocketMap);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        for (String id : webSocketMap.keySet()) {
            if (webSocketMap.get(id).isOpen()) {
                webSocketMap.remove(id);
            }
        }
        log.info("连接断开");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("收到消息:" + message);
    }

    /**
     * @param error 异常对象
     */
    @OnError
    public void onError(Throwable error) {
        log.error("WebSocket错误,原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String id, String message) {
        log.info("发送消息到:" + id + "    内容:" + message);
        Session session = webSocketMap.get(id);
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            } else {
                webSocketMap.remove(id);
            }
        } catch (IOException e) {
            log.error("推送失败:{}", e);
        }
    }

    public void sendToAll(String message) {
        log.info("发送到全部连接:" + webSocketMap);
        for (String id : webSocketMap.keySet()) {
            sendMessage(id, message);
        }
    }

}
