package com.fs.websocket;

import com.alibaba.fastjson.JSONObject;
import com.fs.websocket.bean.MsgBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/imserver/{uid}")
@Component
public class WebSocketServer {
    Logger logger= LoggerFactory.getLogger(getClass());
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public  void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    //给指定用户发送信息
    public  void sendInfo(String id, String message){
        Session session = sessionPools.get(id);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String uid){
        sessionPools.put(uid, session);
//        System.out.println(uid + "加入webSocket！当前人数为" + sessionPools.size());
        logger.info(uid + "加入webSocket！当前人数为" + sessionPools.size());
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "uid") String uid){
        sessionPools.remove(uid);
        System.out.println(uid + "断开webSocket连接！当前人数为" +  sessionPools.size());
        logger.info(uid + "断开webSocket连接！当前人数为" +  sessionPools.size());
    }


    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException{
        MsgBean msg=(MsgBean) JSONObject.parseObject(message, MsgBean.class);
        message = "客户端：" + message + ",已收到";
        //System.out.println("收到消息"+message);
        Session session;
        switch (msg.getCmd()){
            case "heartbeat":
                session=sessionPools.get(msg.getUserId());
                if(session!=null){
                    //System.out.println("发送消息"+message);
                    sendMessage(session, JSONObject.toJSONString(msg));
                }
                break;
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        //throwable.printStackTrace();
    }


}
