package com.wishurgift.entry.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.Arrays;

@Slf4j
@WebFilter("/*")
public class SimpleCORSFilter implements Filter {

    private final String allowedMethods;
    private final String allowedHeader;

    public SimpleCORSFilter() {
        allowedMethods = String.join(",", Arrays.asList(
                "GET",
                "POST",
                "PUT",
                "PATCH",
                "DELETE",
                "PATCH",
                "HEAD",
                "OPTIONS"
        ));
        allowedHeader = String.join(",", Arrays.asList(
                "Content-Type",
                "X-Requested-With",
                "Origin",
                "Access-Control-Request-Method",
                "Access-Control-Request-Headers",
                "Accept",
                "Authorization"
        ));
    }

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
        log.info("Cors filter enabled");
    }

    public void doFilter(final ServletRequest request,
                         final ServletResponse response,
                         final FilterChain chain
    ) throws IOException, ServletException {
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
            final HttpServletResponse httpResponse = (HttpServletResponse) response;

            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Methods", allowedMethods);
            httpResponse.setHeader("Access-Control-Max-Age", "360000");
            httpResponse.setHeader("Access-Control-Allow-Headers", allowedHeader);

            if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
                httpResponse.setStatus(Response.Status.ACCEPTED.getStatusCode());
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}