package com.njcn.gateway.utils;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.gateway.enums.GateWayEnum;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年12月16日 10:26
 */
public class ResponseUtils {

    public static Mono<Void> writeErrorInfo(ServerHttpResponse response, GateWayEnum gateWayEnum) {
//        switch (gateWayEnum) {
//            case NO_AUTHORIZATION:
//            case PARSE_TOKEN_EXPIRE_JWT:
//                response.setStatusCode(HttpStatus.OK);
//                break;
//            case PARSE_TOKEN_FORBIDDEN_JWT:
//                response.setStatusCode(HttpStatus.FORBIDDEN);
//                break;
//            default:
//                response.setStatusCode(HttpStatus.BAD_REQUEST);
//                break;
//        }
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        response.getHeaders().set("Cache-Control", "no-cache");
        String body = JSONUtil.toJsonStr(
                HttpResultUtil.assembleResult(gateWayEnum.getCode(), null, StringUtil.EMPTY + gateWayEnum.getMessage())
        );
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> DataBufferUtils.release(buffer));
    }

}

