package com.malk.server.common;

import com.malk.base.BaseDto;
import lombok.Builder;
import lombok.Data;

/**
 * 定义返回值结构信息
 * - java使用了未经检查或不安全的操作，编译会有打印，如泛型 T
 * 单个文件屏蔽: @SuppressWarnings("unchecked") 。注解在类上编辑就不会有输出
 * 插件显示警告: 配置 -Xlint:unchecked, 显示具体报错警告位置, 如 Map, List 也会报警告
 */
@Data
@Builder
public class McR<T> extends BaseDto {

    private boolean success;
    private String code;
    private String message;
    private T data;

    // 错误来源
    private String source;

    /// 错误实例 ///

    public McR(McREnum rEnum, T data) {
        this(rEnum.isSuc(), rEnum.getCode(), rEnum.getMsg(), data);
    }

    public McR(boolean success, String code, String message, T data, String source) {
        this.success = success;
        this.code = code;
        this.message = message;
        this.data = data;
        this.source = source;
    }

    public McR(boolean success, String code, String message, T data) {
        this(success, code, message, data, null);
    }

    /// 静态访问 ///

    public static McR R(McREnum rEnum) {
        return new McR(rEnum, null);
    }

    public static McR R(McREnum rEnum, Object data) {
        return new McR(rEnum, data);
    }

    public static McR R(boolean success, String code, String message, Object data, String source) {
        return new McR(success, code, message, data, source);
    }

    /// 快速访问: 实例 ///

    public static McR error(String code, String message) {
        return R(false, code, message, null, null);
    }

    public static McR errorParam(String message) {
        return error(McREnum.VALIDATED_PARAM.getCode(), message);
    }

    public static McR errorAccess(String message) {
        return error(McREnum.VALIDATED_ACCESS.getCode(), message);
    }

    public static McR errorAuth(String message) {
        return error(McREnum.NOT_AUTHORIZED.getCode(), message);
    }

    public static McR errorVendor(String message, String source) {
        return R(false, McREnum.VENDOR_ERROR.getCode(), message, null, source);
    }

    public static McR errorUnknown(String message) {
        return error(McREnum.UNKNOWN_EXCEPTION.getCode(), message);
    }

    /// 快速访问: 枚举 ///

    public static McR success() {
        return R(McREnum.SUCCESS);
    }

    public static McR success(Object data) {
        return R(McREnum.SUCCESS, data);
    }

    public static McR errorIgnore() {
        return R(McREnum.IGNORE_EXECUTE);
    }

    public static McR errorToken() {
        return R(McREnum.TOKEN_INVALID);
    }

    public static McR errorNullPointer() {
        return R(McREnum.NULL_POINTER);
    }
}

