package cc.smtweb.framework.core.common;

import cc.smtweb.framework.core.exception.ExceptionMessage;

import java.util.Date;

/**
 * 〈返回结果集〉
 *
 * @author kevin
 * @since 1.0.0
 */
public class R extends SwMap {
    protected R() {
        this(0);
    }

    protected R(int code) {
        put("now", new Date());
        put("code", code);
    }

    public static R success() {
        return new R();
    }

    public static R success(Object data) {
        return new R().put("data", data);
    }

    public static R success(String name, Object data) {
        return new R().put(name, data);
    }

    public static R error() {
        return error(ExceptionMessage.INNER_ERROR.getMsg());
    }

    public static R error(String msg) {
        R r = new R(ExceptionMessage.INNER_ERROR.getCode());
        r.put("msg", msg);
        return r;
    }

    public static R error(int code, String msg) {
        R r = new R(code);
        r.put("msg", msg);
        return r;
    }

    public static R errorf(String format, Object... args) {
        R r = new R(ExceptionMessage.INNER_ERROR.getCode());
        r.put("msg", String.format(format, args));
        return r;
    }

//    public static R error(ExceptionMessage cm) {
//        R r = new R(cm.getCode());
//        r.put("msg", cm.getMsg());
//        return r;
//    }

//    public static R error(ExceptionMessage cm, Throwable ex) {
//        R r = new R(cm.getCode());
//        r.put("msg", cm.getMsg());
//        r.put("exception", ex.getMessage());
//        return r;
//    }

    public static R error(String msg, Throwable ex) {
        R r = new R(ExceptionMessage.INNER_ERROR.getCode());
        r.put("msg", msg);
        r.put("exception", ex.getMessage());
        ex.printStackTrace();
        return r;
    }

    public static R error(ExceptionMessage cm, String msg) {
        R r = new R(cm.getCode());
        r.put("msg", msg);
        return r;
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public R putNotNull(String key, Object value) {
        if (value != null) {
            super.put(key, value);
        }

        return this;
    }

    public void setMessage(ExceptionMessage cm) {
        this.put("code", cm.getCode());
        this.put("msg", cm.getMsg());
    }

    public void setData(Object data) {
        this.put("data", data);
    }

    public int readCode() {
        return this.readInt("code");
    }

    public String readMsg() {
        return this.readString("msg");
    }

    public boolean readSuccess() {
        return this.readInt("code", -1) == 0;
    }
}
