package com.chenyang.nse.bussiness.webtools.json;

import com.chenyang.nse.bussiness.webtools.dao.PageInfo;
import com.chenyang.nse.bussiness.webtools.tools.msg.MesUtil;
import java.util.List;

public class RespHelper {
   public static String errorTrackSpace(Exception e) {
      StringBuffer sb = new StringBuffer();
      if (e != null) {
         for(StackTraceElement element : e.getStackTrace()) {
            sb.append("\n").append(element);
         }
      }

      return sb.length() == 0 ? null : sb.toString();
   }

   public static <T> Response<T> successResp() {
      return createResp(true, "POP_00014", "成功。");
   }

   public static <T> Response<T> successResp(T payload) {
      Response<T> resp = successResp();
      resp.flag = true;
      resp.setData(payload);
      return resp;
   }

   public static <T> Response<T> successResp(T payload, int totalCount) {
      Response<T> resp = successResp();
      resp.flag = true;
      resp.setData(payload);
      resp.setTotalCount(totalCount);
      return resp;
   }

   public static Response updateResp(PageInfo pagination, List list) {
      ListSlice<?> slice = new ListSlice(pagination.getCount(), list);
      ResponseObj resp = successRespObj();
      resp.setData(slice);
      resp.setTotal(slice.getTotal());
      return resp;
   }

   public static <T> Response<T> exceptionResp(Exception ex) {
      return createResp(ErrCode.SERVER_EXCEPTION.getCode(), errorTrackSpace(ex));
   }

   public static <T> Response<T> exceptionResp(String exStr) {
      return createResp(ErrCode.SERVER_EXCEPTION.getCode(), exStr);
   }

   public static <T> Response<T> paramErrResp() {
      return createResp(ErrCode.REQ_PARAM_ERROR.getCode(), ErrCode.REQ_PARAM_ERROR.getDesc());
   }

   public static <T> Response<T> errResp(ErrCode errCode) {
      return createResp(errCode.getCode(), errCode.getDesc());
   }

   public static <T> Response<T> createResp(String code, String description) {
      return new Response<T>(code, description);
   }

   public static <T> Response<T> createResp(boolean flag, String code, String description) {
      return new Response<T>(flag, code, description);
   }

   public static <T> ResponseObj<T> successRespObj() {
      return createRespObj("POP_00014", MesUtil.getMsg("POP_00014", new String[0]));
   }

   public static <T> ResponseObj<T> createRespObj(String code, String description) {
      return new ResponseObj<T>(true, code, description);
   }
}
