package jp.kobe_u.cs27.newse.medicalcheck.controller;

import java.util.List;

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.annotation.Validated;
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 jp.kobe_u.cs27.newse.medicalcheck.dto.PersonDto;
import jp.kobe_u.cs27.newse.medicalcheck.dto.PersonForm;
import jp.kobe_u.cs27.newse.medicalcheck.service.PersonManager;

@Controller
public class PersonController {
    @Autowired
    PersonManager pm;

    @PostMapping("/persons")
    public String addPerson(@ModelAttribute @Validated PersonForm form, BindingResult result, Model model) {
        pm.addPerson(form.toEntity());

        return "redirect:/persons";
    }

    @GetMapping("/persons/{number}")
    public String showPerson(@PathVariable Long number, Model model) {
        PersonDto p = pm.getPerson(number);
        model.addAttribute("person", p);
        return "person";
    }

    @GetMapping("/persons")
    public String showAllPersons(Model model) {
        List<PersonDto> personList = pm.getAllPersons();
        model.addAttribute("plist", personList);
        return "list";
    }

    @GetMapping("/persons/register")
    public String showPersonForm(Model model) {
        model.addAttribute("PersonForm", new PersonForm());
        return "register";
    }

    @GetMapping("/persons/{number}/delete")
    public String deletePerson(@PathVariable Long number, Model model) {
        pm.deletePerson(number);
        
        return "redirect:/persons";
    }

    @GetMapping("/persons/{number}/update")
    public String showUpdateForm(@PathVariable Long number, Model model) {
        PersonDto p = pm.getPerson(number);
        model.addAttribute("PersonForm", p);
        return "update";
    }

    @PostMapping("/persons/{number}/update")
    public String updatePerson(@ModelAttribute @Validated PersonForm form, @PathVariable Long number, Model model) {
        pm.updatePerson(number, form.toEntity());

        return "redirect:/persons";
    }


}