package p2.ws.restful;

import p2.p2server.P2Server;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.Properties;

@Provider
@PreMatching
public class CORSResponseFilter implements ContainerResponseFilter {
    public static String allowOrigin;

    private static boolean init;

    private static boolean enabletoken;

    private static String token = "";

    public void filter(ContainerRequestContext paramContainerRequestContext, ContainerResponseContext paramContainerResponseContext) throws IOException {
        if (!init) {
            init = true;
            Properties properties;
            token = (properties = P2Server.getP2Server().getConfig()).getProperty("p2.ws.token", "");
            enabletoken=properties.getProperty("p2.ws.enabletoken", "false").equalsIgnoreCase("true");
            allowOrigin = properties.getProperty("p2.ws.alloworigin", "http://localhost");
        }
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Origin", allowOrigin);
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,cache-control");

//        if (enabletoken) {
//            String str3 = (String) paramContainerRequestContext.getUriInfo().getQueryParameters().getFirst("ts");
//            String str1 = (String) paramContainerRequestContext.getUriInfo().getQueryParameters().getFirst("token");
//            if (!token.isEmpty())
//                str3 = str3 + "|" + token;
//            if (str3 == null || str3.isEmpty() || str1 == null || str1.isEmpty()) {
//                null.setStatus(401);
//                null.getOutputStream().close();
//            }
//            String str2;
//            if (!(str2 = DigestUtils.md5Hex(str3)).equals(str1)) {
//                null.setStatus(401);
//                null.getOutputStream().close();
//            }
//        }
    }
}
