package com.xunwang.education.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xunwang.education.config.GetHttpParamsConfigurator;
import com.xunwang.education.entity.MpInnerMsg;
import com.xunwang.education.entity.socket.Commucation;
import com.xunwang.education.entity.socket.Message;
import com.xunwang.education.service.MpInnerMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/education/chat", configurator = GetHttpParamsConfigurator.class)
@Component
@Slf4j
public class ChatEndpoint {

    @Resource
    private MpInnerMsgService innerMsgService;

    //用来存储每个用户客户端对象的ChatEndpoint对象
    private static Map<String, ChatEndpoint> USER_CLIENT_MAP = new ConcurrentHashMap<>();

    //声明session对象，通过对象可以发送消息给指定的用户
    private Session session;

    private String uid;

    // 连接建立
    @OnOpen
    public String onOpen(Session session, EndpointConfig config) {
        this.session = session;
        String uid = (String) config.getUserProperties().get("uid");
        this.uid = uid;
        USER_CLIENT_MAP.put(uid, this);
        log.info("已连接",USER_CLIENT_MAP.toString());
        return "连接成功";
    }

    //收到消息
    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Message message1 = mapper.readValue(message, Message.class);
        String toUid = message1.getFromUid();
        String context = message1.getContext();

        USER_CLIENT_MAP.get(toUid).session.getBasicRemote().sendText(context);
    }

    // 向（被邀请方）发送消息
    public void sendInvited(String uid, String id, String commucation, String type) throws IOException {
        String text = commucation + id;
        MpInnerMsg mpInnerMsg = new MpInnerMsg();
        mpInnerMsg.setUid(uid).setMsgTitle(type).setMsgContent(text);
        innerMsgService.save(mpInnerMsg);
        ChatEndpoint chatEndpoint = USER_CLIENT_MAP.get(uid);
        if (chatEndpoint != null) {
            USER_CLIENT_MAP.get(uid).session.getBasicRemote().sendText(text);
        }
    }

//     关闭
    @OnClose
    public void onClose(Session session) {
        USER_CLIENT_MAP.remove(uid);
    }
}
