package net.northking.cctp.mobile.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import net.northking.cctp.mobile.constants.DeviceConstants;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

public class WSRequest {
    /**
     * 会话ID
     */
    private String sessionId;
    /**
     * 请求指令
     */
    private String cmd;
    /**
     * 请求数据
     */
    private Map<String,Object> data;

    /**
     * 用户token
     */
    private String userToken;

    public String getUserToken() {
        return userToken;
    }

    public void setUserToken(String userToken) {
        this.userToken = userToken;
    }


    public WSRequest sessionId(String sessionId){
        this.sessionId = sessionId;
        return this;
    }
    public WSRequest cmd(String cmd){
        this.cmd = cmd;
        return this;
    }
    public WSRequest requestId(String requestId){
        withData(DeviceConstants.KEY_REQUEST_ID,requestId);
        return this;
    }
    public WSRequest withData(String key, Object value){
        if(null == this.data){
            data = new HashMap<>();
        }
        this.data.put(key,value);
        return this;
    }

    public WSRequest withData(Map<String,Object> data){
        if(null == this.data){
            this.data = new HashMap<>();
        }
        if (!CollectionUtils.isEmpty(data)) {
            this.data.putAll(data);
        }
        return this;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public String getCmd() {
        return cmd;
    }
    public Object getDataValue(String key){
        if(StringUtils.isBlank(key) || null == data){
            return null;
        }
        return  data.get(key);
    }
    @JsonIgnore
    public String getRequestId(){
        return (String)getDataValue(DeviceConstants.KEY_REQUEST_ID);
    }

    public void setCmd(String cmd) {
        this.cmd = cmd;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append(DeviceConstants.SESSION_ID, sessionId)
                .append(DeviceConstants.CMD, cmd)
                .append(DeviceConstants.DATA, data)
                .toString();
    }

    public static WSRequest newRequest(){
        return new WSRequest();
    }
}
