package de.jottyfan.camporganizer.module.migration;

import jakarta.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.validation.FieldError;
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;

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

	@Autowired
	private MigrationService service;

	/**
	 * to the login page
	 *
	 * @return
	 */
	@GetMapping("/migration/login")
	public String getLogin(Model model) {
		model.addAttribute("bean", new MigrationBean());
		return "/migration/login";
	}

	@PostMapping("/migration/loginold")
	public String loginOld(@Valid @ModelAttribute("bean") MigrationBean bean, final BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
			return "/migration/login";
		} else if (service.checkLogin(bean)) {
			service.migrate(bean);
			return "redirect:/dashboard";
		} else {
			bindingResult.addError(new FieldError("password", "password", "Dein Passwort scheint falsch zu sein, oder den Benutzer gibt es nicht."));
			return "/migration/login";
		}
	}
}
