package com.union.ai.api.result;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.union.ai.api.enums.ErrorEnum;

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

/**
 * Created by fengjr on 2015/6/2 0002.
 */
public class AppResponse<T> implements Serializable {
    private static final Map NO_ERROR = null;
    private static final Map FAILURE = ImmutableMap.of("code", -1, "message", "内部错误");

    private boolean success;
    private T data;
    private Map error;

    public Map getError() {
        return error;
    }

    public void setError(Map error) {
        this.error = error;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static AppResponse ok() {
        return new AppResponse(true, NO_ERROR, null);
    }

    public static AppResponse ok(Object content) {
        return new AppResponse(true, NO_ERROR, content);
    }


    public static AppResponse bad() {
        return new AppResponse(false, FAILURE, null);
    }

    public static AppResponse bad(ErrorEnum errorEnum) {
        return new AppResponse(false, ImmutableMap.of("code", errorEnum.getCode(), "message", errorEnum.getMessage()), null);
    }

    public static AppResponse bad(String errorMsg) {
        return new AppResponse(false, ImmutableMap.of("code", -1, "message", errorMsg), null);
    }

    public static AppResponse bad(String errorMsg, Object content) {
        return new AppResponse(false, ImmutableMap.of("code", -1, "message", errorMsg), content);
    }

    public static AppResponse bad(int errorCode, String errorMsg) {
        return new AppResponse(false, ImmutableMap.of("code", errorCode, "message", errorMsg), null);
    }

    public static AppResponse bad(int errorCode, String errorMsg, Object content) {
        return new AppResponse(false, ImmutableMap.of("code", errorCode, "message", errorMsg), content);
    }

    private AppResponse(boolean success, Map error, T data) {
        this.success = success;
        this.error = error;
        this.data = data;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }


}

