package org.hso.ecommerce.controller;

import java.util.Optional;

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

import org.hso.ecommerce.entities.user.User;
import org.hso.ecommerce.repos.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/")
public class LoginController {

	@Autowired
	private final UserRepository userRepository = null;

	@GetMapping("login")
	public String login() {
		return "login";
	}

	@PostMapping("login")
	public String loginPost(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {

		String gto = (String) session.getAttribute("afterLogin");

		Optional<User> user = userRepository.findByEmail(username);
		if (!user.isPresent()) {
			request.setAttribute("error", "Die Email Adresse falsch.");
			response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
			return "login";
		}

		if (!user.get().validatePassword(password)) {
			request.setAttribute("error", "Das Passwort ist falsch.");
			response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
			return "login";
		}

		if (!user.get().isActive) {
			request.setAttribute("error", "Dieses Konto ist deaktiviert..");
			response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
			return "login";
		}

		session.setAttribute("userId", user.get().getId());

		if (gto != null && gto.startsWith("/")) {
			return "redirect:" + gto;
		} else {
			return "redirect:/";
		}
	}

	@PostMapping("logout")
	public String logoutPost(HttpServletResponse response, HttpSession session) {
		session.removeAttribute("userId");
		return "redirect:/";
	}
}
