package com.wecloud.im.ws.model;

import io.geekidea.springbootplus.framework.common.api.ApiCode;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;

import com.wecloud.dispatch.util.ActionRequestHolder;
import com.wecloud.im.ws.enums.WsResponseCmdEnum;

/**
 * @Description websocket服务端响应消息和下方消息的封装对象
 * @Author hewei hwei1233@163.com
 * @Date 2019-12-05
 */
@Data
@Accessors(chain = true)
public class WsResponse<T> implements Serializable {

    /**
     * 枚举类 {@link com.wecloud.im.ws.enums.WsResponseCmdEnum WsResponseCmdEnum} 请求uri的编码
     * 由于webSocket使用同一个通道发送数据，需要区分不同类型请求
     */
    private Integer cmd;

    /**
     * 状态码
     */
    private int code;

    /**
     * 状态描述
     */
    private String msg;

    /**
     * json数据
     */
    private T data;

    /**
     * 请求id, 以判空是否发送成功, 服务端处理完成后返回
     * 可以以当前时间戳为id
     */
    private String reqId;


    public static WsResponse<Boolean> result(ApiCode apiCode) {
        return result(apiCode, true);
    }

    public static <T> WsResponse<T> result(ApiCode apiCode, T data) {
        return result(apiCode, "", data);
    }

    public static <T> WsResponse<T> result(ApiCode apiCode, String message, T data) {
        return result(WsResponseCmdEnum.RES.getCmdCode(), apiCode, message, data);
    }

    public static <T> WsResponse<T> result(Integer cmd, ApiCode apiCode, String message, T data) {
        WsResponse<T> response = new WsResponse<>();
        response.setCmd(cmd).setCode(apiCode.getCode()).setMsg(message).setData(data);
        if (ActionRequestHolder.getActionRequest() != null) {
            response.setReqId(ActionRequestHolder.getReqId());
        }
        return response;
    }

    public static WsResponse<Map<String, Boolean>> ok() {
        return ok(Collections.emptyMap());
    }

    public static <T> WsResponse<T> ok(T data) {
        return result(ApiCode.SUCCESS, data);
    }

    public static WsResponse<Map<String, Boolean>> fail() {
        return ok(Collections.emptyMap());
    }

    public static WsResponse<Boolean> fail(String message) {
        return result(ApiCode.FAIL, message, false);
    }

    public static <T> WsResponse<T> fail(ApiCode apiCode) {
        return result(apiCode, "", null);
    }

    public static <T> WsResponse<T> fail(ApiCode apiCode, String message) {
        return result(apiCode, message, null);
    }


}
