package com.mzh.library.controller;

import com.mzh.library.entity.AuthenticatedUser;
import com.mzh.library.util.SessionAttributes;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(LogoutServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            AuthenticatedUser user = currentUser(session);
            if (user != null) {
                LOGGER.info("Logout userId=" + user.getId() + " role=" + user.getRole().getCode());
            }
            session.invalidate();
        }

        response.sendRedirect(request.getContextPath() + "/login");
    }

    private AuthenticatedUser currentUser(HttpSession session) {
        Object value = session.getAttribute(SessionAttributes.AUTHENTICATED_USER);
        return value instanceof AuthenticatedUser ? (AuthenticatedUser) value : null;
    }
}
