package org.hso.ecommerce.components;

import org.hso.ecommerce.repos.user.UserRepository;
import org.hso.ecommerce.entities.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Optional;

@Component
public class LoginIntercepter implements HandlerInterceptor {

    @Autowired
    private final UserRepository userRepository = null;

    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object userId = session.getAttribute("userId");
        Optional<User> user = null;

        if (request.getRequestURI().startsWith("/user/")) {
            System.out.println("USER");

            if (userId == null) {
                session.setAttribute("afterLogin", request.getRequestURI());
                response.sendRedirect("/login");
                return false;
            }
        }

        if (request.getRequestURI().startsWith("/intern/")) {
            System.out.println("intern");

            if (userId == null) {
                session.setAttribute("afterLogin", request.getRequestURI());
                response.sendRedirect("/login");
                return false;
            }

            user = userRepository.findById((Long) userId);

            if(user.isPresent() && !user.get().isEmployee)
            {
                session.setAttribute("afterLogin", request.getRequestURI());
                response.sendRedirect("/");
                return false;
            }
        }

        if (!request.getRequestURI().startsWith("/login")) {
            session.removeAttribute("afterLogin");
        }

        if (userId != null) {
            if (user == null)
                user = userRepository.findById((Long) userId);
            user.ifPresent(value -> request.setAttribute("user", value));
        }

        return true;
    }

    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception exception) throws Exception {
    }
}
