package org.academiadecodigo.enuminatti.helloworldspringmvc.controller;

import org.academiadecodigo.enuminatti.helloworldspringmvc.models.User;
import org.academiadecodigo.enuminatti.helloworldspringmvc.services.UserService;
import org.academiadecodigo.enuminatti.helloworldspringmvc.utils.Attributes;
import org.academiadecodigo.enuminatti.helloworldspringmvc.utils.Routes;
import org.academiadecodigo.enuminatti.helloworldspringmvc.utils.Views;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.w3c.dom.Attr;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

@Controller
@SessionAttributes(Attributes.LOGGED_USER)
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET, value = {Routes.LOGIN, Routes.ROOT})
    public ModelAndView showLogin() {
        ModelAndView modelAndView = new ModelAndView(Views.LOGIN);
        modelAndView.addObject(Attributes.USER, new User());
        return modelAndView;
    }

    @RequestMapping(method = RequestMethod.POST, value = {Routes.LOGIN, Routes.ROOT})
    public String doLogin(Model model, @Valid @ModelAttribute(Attributes.USER) User user,
                          BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return Views.LOGIN;
        }

        // If auth succeeds, render a new view
        if (userService.authenticate(user.getUsername(), user.getPassword())) {
            model.addAttribute(Attributes.LOGGED_USER, user);
            return Routes.redirect(Routes.BOOTCAMPS + Routes.LIST);

            // If auth fails, render the same view with error message
        } else {
            model.addAttribute(Attributes.AUTH_FAILURE, "Authentication Failure");
            return Views.LOGIN;
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = Routes.LOGOUT)
    public String doLogout(Model model, SessionStatus status, HttpSession session) {
        if (model.containsAttribute(Attributes.LOGGED_USER)) {
            status.setComplete();
            session.removeAttribute(Attributes.LOGGED_USER);
        }

        return Routes.redirect(Routes.ROOT);
    }
}
