package com.njzscloud.common.ws.support;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.njzscloud.common.core.jackson.Jackson;
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 java.util.List;

/**
 * websocket 消息内容
 */
@Slf4j
@Getter
@Setter
@Accessors(chain = true)
public class WsMsg {
    /**
     * 发送方
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private User from;

    /**
     * 接收方
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private List<User> to;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String action;

    /**
     * 事件
     */
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String event;

    /**
     * 数据内容
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Object data;

    public static WsMsg of(Wsdoor wsdoor, TextMessage message) {
        String payload = message.getPayload();
        try {
            WsMsg wsMsg = Jackson.toBean(payload, WsMsg.class);
            if (wsMsg != null) {
                wsMsg.setFrom(new User()
                    .setUid(wsdoor.getUid())
                    .setCid(wsdoor.getCid())
                );
            }
            return wsMsg;
        } catch (Exception e) {
            log.error("WebSocket 消息反序列化失败, 数据: {}", payload, e);
            return null;
        }
    }

    @Override
    public String toString() {
        return Jackson.toJsonStr(this);
    }

    public <T> T extractData(Class<T> clazz) {
        return Jackson.toBean(Jackson.toJsonStr(data), clazz);
    }

    @Getter
    @Setter
    @ToString
    @Accessors(chain = true)
    public static class User {
        /**
         * 用户 Id
         */
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private Long uid;
        /**
         * 客户端 Id
         */
        @JsonInclude(JsonInclude.Include.NON_EMPTY)
        private String cid;
    }
}
