import com.greenfoxacademy.pet_shelter.models.Error;
import com.greenfoxacademy.pet_shelter.models.Human;
import com.greenfoxacademy.pet_shelter.services.HumanService;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
@Controller
public class MainController {
private HumanService humanService;
@Autowired
public MainController(HumanService humanService) {
this.humanService = humanService;
}
@GetMapping("/list-humans")
public String listHumans
(Model model
) {
model.addAttribute("humans", humanService.returnAllHuman());
return "main";
}
@GetMapping("/add-human")
public String addHuman
(Model model
) {
model.addAttribute("human", new Human());
return "modify";
}
@PostMapping("/add-human")
public String addHuman
(@ModelAttribute Human human, Model model
) {
if (human.getName() == null || human.getAge() == 0 || human.getName().isEmpty()) {
model.
addAttribute("error",
new Error("Something went wrong, please check if the fields are filled out or use another name, because the name is already taken"));
model.addAttribute("human", human);
return "modify";
}
humanService.saveHuman(human);
return "redirect:/list-humans";
}
@GetMapping("/delete/{id}")
public String deleteHuman
(@PathVariable
Long id
) throws NotFoundException
{
humanService.deleteHuman(id);
return "redirect:/list-humans";
}
@GetMapping("/edit/{id}")
public String editHuman
(@PathVariable
Long id, Model model
) {
model.addAttribute("human", humanService.returnHumanById(id));
model.addAttribute("isEdit", true);
return "modify";
}
@PostMapping("/edit/{id}")
public String editHuman
(@PathVariable
Long id, @ModelAttribute Human human
) {
human.setId(id);
humanService.editHuman(human);
return "redirect:/list-humans";
}
}