package de.jottyfan.camporganizer.module.registration;

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

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.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.module.camplist.CommonController;

/**
 *
 * @author jotty
 *
 */
@Controller
public class RegistrationController extends CommonController {

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private RegistrationService service;

	@GetMapping("/registration/{fkCamp}")
	public String index(@PathVariable(name = "fkCamp", required = true) Integer fkCamp, Model model) {
		super.setupSession(model, request);
		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);
			return "/registration/registration";
		} else {
			return "/registration/isover";
		}
	}

	@PostMapping("/registration/register")
	public String register(@Valid @ModelAttribute("bean") RegistrationBean bean, final BindingResult bindingResult, Model model) {
		super.setupSession(model, request);
		if (bindingResult.hasErrors()) {
			CampBean campBean = service.getCamp(bean.getFkCamp());
			model.addAttribute("camp", campBean);
			return "/registration/registration";
		}
		Boolean result = service.register(bean, (String) model.getAttribute("currentUser"));
		return result ? "/registration/success" : "/error";
	}

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

	@GetMapping("/registration/remove/{id}")
	public String remove(@PathVariable Integer id, final Model model) {
		super.setupSession(model, request);
		service.removeBooking(id);
		return "redirect:/dashboard";
	}
}
