package de.jottyfan.camporganizer.module.registration;

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.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import de.jottyfan.camporganizer.db.EnumConverter;
import de.jottyfan.camporganizer.module.camplist.CommonController;
import de.jottyfan.camporganizer.module.registration.model.CampBean;
import de.jottyfan.camporganizer.module.registration.model.RegistrationBean;
import jakarta.validation.Valid;

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

	@Autowired
	private RegistrationService service;

	@GetMapping("/registration/{fkCamp}")
	public String index(@PathVariable(name = "fkCamp", required = true) Integer fkCamp, Model model) {
		if (service.campIsNotYetOver(fkCamp)) {
			CampBean campBean = service.getCamp(fkCamp);
			model.addAttribute("camp", campBean);
			RegistrationBean bean = new RegistrationBean();
			bean.setFkCamp(fkCamp);
			bean.setRegisterInKeycloak(true); // we want people to register generally
			model.addAttribute("bean", bean);
			model.addAttribute("sexes", EnumConverter.getSexes());
			model.addAttribute("roles", EnumConverter.getRoles());
			model.addAttribute("wellknown", service.getWellKnownRegistrations(getCurrentUser()));
			return "/registration/registration";
		} else {
			return "/registration/isover";
		}
	}

	/**
	 * userlogin is protected and leads the request to the keycloak login mask if not yet logged in
	 *
	 * @param fkCamp the ID of the camp
	 * @param model the model
	 * @return hen registration page
	 */
	@GetMapping("/userlogin/registration/{fkCamp}")
	public String loginIndex(@PathVariable(name = "fkCamp", required = true) Integer fkCamp, Model model) {
		return index(fkCamp, model);
	}

	@PostMapping("/registration/register")
	public String register(@Valid @ModelAttribute("bean") RegistrationBean bean, final BindingResult bindingResult,
			Model model) {
		if (bindingResult.hasErrors()) {
			for (ObjectError error : bindingResult.getAllErrors()) {
				LOGGER.error("found {}", error);
			}
			CampBean campBean = service.getCamp(bean.getFkCamp());
			model.addAttribute("camp", campBean);
			model.addAttribute("sexes", EnumConverter.getSexes());
			model.addAttribute("roles", EnumConverter.getRoles());
			String currentUser = getCurrentUser();
			if (currentUser != null) {
				model.addAttribute("wellknown", service.getWellKnownRegistrations(currentUser));
			}
			return "/registration/registration";
		}
	  Integer result = service.register(bean, getCurrentUser());
	  if (result < 1) {
	  	LOGGER.error("added less than 1 row on registering {}", bean);
			CampBean campBean = service.getCamp(bean.getFkCamp());
			model.addAttribute("camp", campBean);
			model.addAttribute("sexes", EnumConverter.getSexes());
			model.addAttribute("roles", EnumConverter.getRoles());
			String currentUser = getCurrentUser();
			if (currentUser != null) {
				model.addAttribute("wellknown", service.getWellKnownRegistrations(currentUser));
			}
			return "/registration/registration";
	  }
		return "/registration/success";
	}

	@GetMapping("/registration/cancel/{id}")
	public String cancellation(@PathVariable("id") Integer id, final Model model) {
		model.addAttribute("bean", service.getBooking(id));
		return "/registration/cancellation";
	}

	@GetMapping("/registration/revoke/{id}")
	public String revoke(@PathVariable("id") Integer id, final Model model) {
		service.revokeBooking(id, true);
		return "redirect:/dashboard";
	}

	@GetMapping("/registration/unrevoke/{id}")
	public String unrevoke(@PathVariable("id") Integer id, final Model model) {
		service.revokeBooking(id, false);
		return "redirect:/dashboard";
	}

	@GetMapping("/registration/toggleconsent/{id}")
	public String toggleConsent(@PathVariable("id") Integer id, final Model model) {
		service.toggleConsent(id);
		return "redirect:/dashboard";
	}
}
