package com.sagacloud.filters;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.Provider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;


/**
 * Created by wo on 8/20/19.
 */
@Priority(0)
@Provider
@PreMatching
public class SetPjInUrlFilter implements ContainerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(SetPjInUrlFilter.class);
    
    @Context
    private HttpServletRequest servletRequest;
    
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
    	
//    	if(null != servletRequest) {
//    		String raddr = servletRequest.getRemoteAddr();
//    		String rurl = servletRequest.getRequestURI();
//    		log.info("requesterIP : " + raddr + ", requestURL : "+ rurl);
//    	}
    	
        InputStream bodyStream = requestContext.getEntityStream();
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(bodyStream, writer, "utf-8");
            JSONObject json = JSONObject.parseObject(writer.toString());
            if(json == null){
                return;
            }
            if(json.get("projectId") != null){
                UriBuilder builder = requestContext.getUriInfo().getRequestUriBuilder();
                builder.replaceQueryParam("projectId", json.getString("projectId"));
                requestContext.setRequestUri(builder.build());
            }
            if (!requestContext.getUriInfo().getPath().contains("mng/building/create")){
                json.fluentRemove("projectId");
                requestContext.setEntityStream(new ByteArrayInputStream(json.toString(SerializerFeature.WriteMapNullValue).toString().getBytes()));
                return;
            }
            requestContext.setEntityStream(new ByteArrayInputStream(writer.toString().getBytes()));
        } catch (IOException e) {
            log.error("", e);
        }
    }
}
