package de.jottyfan.camporganizer.module.camplist;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import de.jottyfan.camporganizer.module.registration.KeycloakRepository;

/**
 *
 * @author jotty
 *
 */
@Controller
public class CamplistController extends CommonController {
	private static final Logger LOGGER = LogManager.getLogger(CamplistController.class);

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private KeycloakRepository keycloak;

	@Autowired
	private CamplistService service;

	@GetMapping("/camplist")
	public String index(Model model) {
		super.setupSession(model, request);
		model.addAttribute("camps", service.getAllCamps(true));
		return super.isLoggedIn(request) ? dashboard(model) : "/camplist";
	}

	@GetMapping("/dashboard")
	public String dashboard(Model model) {
		super.setupSession(model, request);
		model.addAttribute("mybookings", service.getBookingsOf(super.getCurrentUser(request)));
		model.addAttribute("bookingBean", new BookingBean());
		model.addAttribute("keycloakProfileUrl", keycloak.getUserClientUrl());
		model.addAttribute("camps", service.getAllCamps(true));
		return "/dashboard";
	}

	@PostMapping("/dashboard/update")
	public String updateBooking(Model model, @ModelAttribute BookingBean bean) {
		service.update(bean);
		return dashboard(model);
	}

	@GetMapping("/logout")
	public String getLogout(HttpServletRequest request) throws ServletException {
		request.logout();
		LOGGER.debug("logout");
		return "redirect:/";
	}
}
