package com.eactive.httpmockserver.login.controller;

import com.eactive.httpmockserver.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 일반 로그인을 처리하는 컨트롤러 클래스
 *
 * @author
 * @version 1.0
 */
@Controller
public class LoginController {

    public static final String LOGIN_MESSAGE = "loginMessage";

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 로그인 화면으로 들어간다
     *
     * @return 로그인 페이지
     */
    @GetMapping("/login")
    public String loginUsrView(HttpSession session,
                               ModelMap model) {

        if (!userService.isInitialized()) {
            return "redirect:/admin_register_view.do";
        }

        String message = (String) session.getAttribute(LOGIN_MESSAGE);
        if (StringUtils.isNotEmpty(message)) {
            model.addAttribute(LOGIN_MESSAGE, message);
        }
        session.setAttribute(LOGIN_MESSAGE, null);

        return "page/login";
    }

    /**
     * 세션타임아웃 시간을 연장한다.
     *
     * @return result - String
     */
    @GetMapping(value = "/refreshSessionTimeout.do", produces = "text/html;charset=utf-8")
    @ResponseBody
    public ResponseEntity<String> refreshSessionTimeout(@RequestParam Map<String, Object> commandMap) {
        return ResponseEntity.ok("success");
    }

    @GetMapping("/actionLogout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && !authentication.getPrincipal().equals("anonymousUser")) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }

        return "redirect:/";
    }

}
