package vn.azteam.tpf.security.apiKey;

import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import vn.azteam.tpf.service.TBCustomerService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import static vn.azteam.tpf.security.contants.Contants.*;

public class ApiKeyFilter extends GenericFilterBean {

    private static final String tpf_API_PREFIX = "/api/";

    private static final String GET_REQUEST_METHOD = "GET";

    private ApiKeyProvider apiKeyProvider;

    public ApiKeyFilter (ApiKeyProvider apiKeyProvider){
        this.apiKeyProvider = apiKeyProvider;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException, UnsupportedEncodingException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestPath = request.getRequestURI();
        String requestMethod = request.getMethod();
        // Allows URLs that not starts with the /api/ prefix.
        if(!requestPath.startsWith(tpf_API_PREFIX)) {
            filterChain.doFilter(request, response);
            return;
        }
        try {
            if (this.hasPermission(request)) {
                filterChain.doFilter(request, response);
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }
    public boolean hasPermission(HttpServletRequest request)
        throws NoSuchAlgorithmException, InvalidKeyException {
        String apiKeyToken = request.getHeader(AUTHORIZATION_API_KEY);
        if (StringUtils.hasText(apiKeyToken)){
            String timestamp = request.getHeader(TIMESTAMP_API_KEY);
            Long customer_id = Long.parseLong(request.getHeader(CUSID_API_KEY));
            return apiKeyProvider.validateToken(customer_id, timestamp, apiKeyToken);
        }
        return false;
    }
}
