package com.lutao.cloud.iot.mqtt.core.server.http.api.result;

import com.alibaba.fastjson.JSONObject;
import com.lutao.cloud.iot.mqtt.core.server.http.api.code.ResultCode;

import org.tio.http.common.HeaderName;
import org.tio.http.common.HeaderValue;
import org.tio.http.common.HttpResponse;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * api Result
 *

 */
public final class Result {
	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	private static final String UTF_8_NAME = UTF_8.name();

	/**
	 * 响应成功
	 *
	 * @param response HttpResponse
	 */
	public static HttpResponse ok(HttpResponse response) {
		ResultCode resultCode = ResultCode.SUCCESS;
		JSONObject json = new JSONObject();
		json.put("code", resultCode.getResultCode());
		return result(response, resultCode, json);
	}

	/**
	 * 响应成功
	 *
	 * @param response HttpResponse
	 * @param data     Object
	 */
	public static HttpResponse ok(HttpResponse response, Object data) {
		ResultCode resultCode = ResultCode.SUCCESS;
		JSONObject json = new JSONObject();
		json.put("code", resultCode.getResultCode());
		json.put("data", data);
		return result(response, resultCode, json);
	}

	/**
	 * 响应失败
	 *
	 * @param response   HttpResponse
	 * @param resultCode ResultCode
	 */
	public static HttpResponse fail(HttpResponse response, ResultCode resultCode) {
		JSONObject json = new JSONObject();
		json.put("code", resultCode.getResultCode());
		return result(response, resultCode, json);
	}

	private static HttpResponse result(HttpResponse response, ResultCode resultCode, JSONObject json) {
		response.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.TEXT_PLAIN_JSON);
		response.setStatus(resultCode.getStatusCode());
		response.setBody(json.toJSONString().getBytes(UTF_8));
		response.setCharset(UTF_8_NAME);
		return response;
	}

}
