package de.jottyfan.camporganizer.module.admin;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.PostMapping;

import de.jottyfan.camporganizer.module.camplist.CommonController;
import de.jottyfan.camporganizer.module.mail.MailBean;

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

	private static final Logger LOGGER = LogManager.getLogger(AdminController.class);

	@Autowired
	private AdminService service;

	@Value("${spring.mail.username}")
	private String from;

	@GetMapping("/admin/mail")
	public String getMail(Model model, HttpServletRequest request) {
		super.setupSession(model, request);
		MailBean mailBean = new MailBean();
		mailBean.setFrom(from);
		mailBean.getTo().add(getCurrentEmail(request));
		model.addAttribute("bean", mailBean);
		return "/admin/mail";
	}

	@PostMapping("/admin/mail/send")
	public String sendMail(@Valid @ModelAttribute("bean") MailBean bean, final BindingResult bindingResult, Model model,
			HttpServletRequest request) {
		super.setupSession(model, request);
		if (bindingResult.hasErrors()) {
			for (ObjectError error : bindingResult.getAllErrors())
			LOGGER.error("error {}: {}", error.getCode(), error.getDefaultMessage());
			return "/admin/mail";
		}
		service.sendMail(bean);
		return "redirect:/admin";
	}

	@GetMapping("/admin")
	public String getMain(Model model, HttpServletRequest request) {
		super.setupSession(model, request);
		return "/admin/main";
	}

	@GetMapping("/admin/main")
	public String getMainDirectly() {
		return "redirect:/admin/main";
	}
}
