package com.ruoyi.common.utils;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.translation.TranslateUtils;

import javax.servlet.http.HttpServletResponse;

// 简易响应
public final class RESP
{
    public static <T> T S(String message, T data)
    {
        return R(HttpStatus.SUCCESS, message, data);
    }

    public static Object S(String message)
    {
        return S(message, null);
    }

    public static <T> T S(T data)
    {
        return S("操作成功", data);
    }

    public static <T> T E(String message, T data)
    {
        return R(HttpStatus.ERROR, message, data);
    }

    public static Object E(String message)
    {
        return E(message, null);
    }

    public static <T> T E(T data)
    {
        return E("操作失败", data);
    }

    private static void translateData(Object data)
    {
        boolean[] ret = { false };
        if(null != data && ServletUtils.requestTranslateData(ret))
        {
            try
            {
                TranslateUtils.translate(data, ret[0]);
            }
            catch(Exception ignored) {}
        }
    }

    public static <T> T R(int code, String message, T data)
    {
        HttpServletResponse response = ServletUtils.getResponse();
        response.setStatus(code);
        response.addHeader("X-Code", "" + code);
        response.addHeader("X-Message", message);
        response.addHeader("X-Timestamp", "" + System.currentTimeMillis());
        response.addHeader("X-Success", "" + (code == HttpStatus.SUCCESS));
        translateData(data);
        return data;
    }

    public static Object R(int code, String message)
    {
        return R(code, message, null);
    }

    private RESP() {}
}
