package com.sagacloud.filters;

import com.google.common.base.Strings;
import com.sagacloud.cache.ProPasCache;
import com.sagacloud.json.JSONObject;
import com.sagacloud.json.JSONValue;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.OssUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

/**
 * Created by wushengzong on 2017/4/19.
 */
@Priority(1)
@Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(AuthorizationRequestFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext) {
        log.info("{} REQUEST URL: {} {}", requestContext.getMethod(), requestContext.getUriInfo().getPath(), requestContext.getUriInfo().getQueryParameters());
        InputStream bodyStream = requestContext.getEntityStream();
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(bodyStream, writer, "utf-8");
            JSONObject json = (JSONObject) JSONValue.parse(writer.toString());
            if (json != null)
                log.info("REQUEST BODY: {}", json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        requestContext.setEntityStream(new ByteArrayInputStream(writer.toString().getBytes()));

        if (OssUtils.getProperty("api.access.needpsw").trim().equalsIgnoreCase("false")) {
            return;
        }

        Map paraMap = requestContext.getUriInfo().getQueryParameters();
        if (requestContext.getUriInfo().getPath().startsWith("mng")) {
            String secret = Strings.nullToEmpty(((List<String>) paraMap.get("secret")).get(0));
            if (secret.equals("A123456")) {
                return;
            } else {
                requestContext.abortWith(Response
                        .status(Response.Status.UNAUTHORIZED)
                        .entity(DpUtils.errorJsonMsg("你没有权限！"))
                        .build());
            }
        }
        if (requestContext.getUriInfo().getPath().contains("property/project/query")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("dict")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("doc")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("infocode")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("custom_infocode/scheme")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("dao")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("access_log")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("calendar")) {
            return;
        }
        if (requestContext.getUriInfo().getPath().startsWith("custom_dict")) {
            return;
        }
        boolean authorized = false;
        String proId = Strings.nullToEmpty(((List<String>) paraMap.get("projectId")) == null ? null : ((List<String>) paraMap.get("projectId")).get(0));
        String secret = Strings.nullToEmpty(((List<String>) paraMap.get("secret")) == null ? null : ((List<String>) paraMap.get("secret")).get(0));
        if (ProPasCache.get(proId) != null && new String(ProPasCache.get(proId)).equals(secret)) {
            authorized = true;
        } else {
            ProPasCache.synCache();
            if (ProPasCache.get(proId) != null && new String(ProPasCache.get(proId)).equals(secret)) {
                authorized = true;
            }
        }

        if (!authorized) {
            requestContext.abortWith(Response
                    .status(Response.Status.UNAUTHORIZED)
                    .entity(DpUtils.errorJsonMsg("你没有权限！"))
                    .build());
        }



    }


}
