package com.njzscloud.common.ws.support;

import cn.hutool.core.map.MapUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Getter
@Setter
@ToString
@Accessors(chain = true)
public class Wsdoor {

    /**
     * 用户 Id
     */
    private final Long uid;
    /**
     * 客户端 Id
     */
    private final String cid;
    /**
     * TOKEN
     */
    private final String token;
    /**
     * 连接会话
     */
    private final WebSocketSession session;

    private Wsdoor(WebSocketSession session) {
        Map<String, Object> attributes = session.getAttributes();
        this.uid = MapUtil.getLong(attributes, "uid");
        this.cid = MapUtil.getStr(attributes, "cid");
        this.token = MapUtil.getStr(attributes, "token");
        this.session = session;
    }

    public static Wsdoor of(WebSocketSession session) {
        return new Wsdoor(session);
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        Wsdoor wsdoor = (Wsdoor) o;
        return Objects.equals(uid, wsdoor.uid) && Objects.equals(cid, wsdoor.cid);
    }

    @Override
    public int hashCode() {
        return Objects.hash(uid, cid);
    }

    /**
     * 发送文本数据
     *
     * @param wsMsg 消息
     */
    public boolean send(WsMsg wsMsg) {
        try {
            if (!session.isOpen()) return false;
            session.sendMessage(new TextMessage(wsMsg.toString()));
            return true;
        } catch (Exception e) {
            log.error("消息发送失败", e);
        }
        return false;
    }
}
