package de.jottyfan.camporganizer.module.confirmation.person;

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;
import de.jottyfan.camporganizer.module.confirmation.person.model.PersonBean;
import jakarta.validation.Valid;

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

	@Autowired
	private PersonService personService;

	@GetMapping("/confirmation/person/{pk}")
	public String getIndex(Model model, @PathVariable("pk") Integer pk) {
		String username = super.getCurrentUser();
		model.addAttribute("currentUser", username);
		model.addAttribute("person", personService.getPerson(username, pk));
		model.addAttribute("camps", personService.getCamps(username));
		model.addAttribute("annotations", personService.getAnnotations(pk));
		model.addAttribute("campPrice", personService.getCampPrice(pk));
		model.addAttribute("progresses", personService.getProgresses());
		return "confirmation/person";
	}

	@PostMapping("/confirmation/person/update")
	public String doUpdate(@Valid @ModelAttribute("person") PersonBean bean, BindingResult bindingResult, Model model) {
		String username = super.getCurrentUser();
		if (bindingResult.hasErrors()) {
			model.addAttribute("currentUser", username);
			model.addAttribute("camps", personService.getCamps(username));
			model.addAttribute("annotations", personService.getAnnotations(bean.getPk()));
			model.addAttribute("campPrice", personService.getCampPrice(bean.getPk()));
			model.addAttribute("progresses", personService.getProgresses());
			return "confirmation/person";
		}
		personService.updatePerson(bean, username);
		return "redirect:/confirmation";
	}
}
