package zall.filter;

import zall.ZalleryServlet;
import zall.bean.User;
import zall.manager.AuthenticationManager;
import zall.page.LoginServlet;
import zall.page.RegisterServlet;
import zutil.ObjectUtil;
import zutil.log.LogUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * This filter will check if user is valid, if not it will redirect to the login page
 */
@WebFilter("/*")
public class AuthenticationFilter implements Filter {
    private static final Logger logger = LogUtil.getLogger();

    private static final String[] WHITELIST = new String[]{
            LoginServlet.URI,
            RegisterServlet.URI
    };

    @Override
    public void init(FilterConfig filterConfig) { }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        User user = AuthenticationManager.getUserSession(((HttpServletRequest) request).getSession());

        // continue the request via the filter pipeline if it is login page or it is a isValid User
        if (AuthenticationManager.isValid(user, (HttpServletRequest) request)) {
            logger.finest("User already authenticated, continuing filter chain.");
            chain.doFilter(request, response);
        } else if (isWhitelisted(requestURI)){
            logger.finer("Continuing filtering chain for whitelisted page: " + requestURI);
            chain.doFilter(request, response);
        } else {
            // do not continue the filter pipeline forward to login page
            logger.fine("User not authenticated, redirecting to login page.");
            ZalleryServlet.redirect(LoginServlet.URI, (HttpServletRequest) request, (HttpServletResponse) response);
        }
    }

    private boolean isWhitelisted(String requestURI) {
        if (ObjectUtil.isEmpty(requestURI))
            return false;

        for (String whitelistURI : WHITELIST) {
            if (requestURI.endsWith(whitelistURI))
                return true;
        }
        return false;
    }

    @Override
    public void destroy() { }
}
