package de.jottyfan.camporganizer.module.business.privileges;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import de.jottyfan.camporganizer.db.jooq.enums.EnumCamprole;
import de.jottyfan.camporganizer.module.business.privileges.model.BusinessPrivilegesBean;
import de.jottyfan.camporganizer.module.camplist.CommonController;
import jakarta.annotation.security.RolesAllowed;
import jakarta.validation.Valid;

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

	@Autowired
	private BusinessPrivilegesService service;

	@GetMapping("/business/privileges")
	@RolesAllowed({ "admin" })
	public String getIndex(Model model) {
		String username = super.getCurrentUser();
		model.addAttribute("currentUser", username);
		model.addAttribute("privileges", service.getPrivileges());
		model.addAttribute("profiles", service.getProfiles(EnumCamprole.director, EnumCamprole.teacher));
		model.addAttribute("bean", new BusinessPrivilegesBean());
		return "business/privileges";
	}

	@PostMapping("/business/privileges/add")
	@RolesAllowed({ "admin" })
	public String getAdd(@Valid @ModelAttribute("bean") BusinessPrivilegesBean bean, BindingResult br, Model model) {
		if (br.hasErrors()) {
			String username = super.getCurrentUser();
			model.addAttribute("currentUser", username);
			model.addAttribute("privileges", service.getPrivileges());
			model.addAttribute("profiles", service.getProfiles(EnumCamprole.director, EnumCamprole.teacher));
			return "business/privileges";
		}
		service.add(bean);
		return "redirect:/business/privileges";
	}

	@GetMapping("/business/privileges/delete")
	@RolesAllowed({ "admin" })
	public String getDelete(@RequestParam("fkCamp") Integer fkCamp, @RequestParam("fkProfile") Integer fkProfile,
			Model model) {
		BusinessPrivilegesBean bean = new BusinessPrivilegesBean();
		bean.setFkCamp(fkCamp);
		bean.setFkProfile(fkProfile);
		service.remove(bean, super.getCurrentUser());
		return "redirect:/business/privileges";
	}
}
