package com.quantgroup.asset.distribution.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;


@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@Slf4j
public class CrosFilter implements Filter {

    private static final Set<String> DISALLOWED_METHOD = new HashSet<>();

    static {
        DISALLOWED_METHOD.add("OPTIONS");
        DISALLOWED_METHOD.add("PUT");
        DISALLOWED_METHOD.add("DELETE");
    }


    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String allowedOrigin = "*";
        response.setHeader("Access-Control-Allow-Origin", allowedOrigin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        String allowedHeaders = "Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization" +
                "Accept,Access-Token,Account,Account-Name,Referer,sec-ch-ua,sec-ch-ua-mobile,sec-ch-ua-platform,User-Agent";
        response.setHeader("Access-Control-Allow-Headers", allowedHeaders);
        response.setHeader("Access-Control-Max-Age", "3600");
        if (DISALLOWED_METHOD.contains(request.getMethod())) {
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
