package de.jottyfan.camporganizer.module.camplist;

import java.security.Principal;

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.camplist.model.BookingBean;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;

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

	@Autowired
	private CamplistService service;

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

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

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

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