package premium_store.controller.controller;

import net.bytebuddy.implementation.bind.MethodDelegationBinder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import premium_store.controller.DTO.FullNationDTO;
import premium_store.controller.DTO.SimpleNationDTO;
import premium_store.service.NationService;

import javax.validation.Valid;

@Controller
@RequestMapping("/nation")
public class NationMvcController {
    private final NationService nationService;

    public NationMvcController(NationService nationService){
        this.nationService = nationService;
    }

    @GetMapping
    public String getNations(Model model){
        model.addAttribute("nations",
                nationService.findAllNations().stream()
                        .map(FullNationDTO::new)
                        .toList());
        return "nation";
    }

    @GetMapping(value = {"/edit", "/edit/{id}"})
    public String editNation(@PathVariable(required = false) Long id, Model model){
        if(id == null || id <= 0){
            model.addAttribute("simpleNationDTO", new SimpleNationDTO());
        }
        else {
            model.addAttribute("nationId", id);
            model.addAttribute("simpleNationDTO", new SimpleNationDTO(nationService.findNation(id)));
        }

        return "nation-edit";
    }

    @GetMapping(value = {"/editTank", "/editTank/{id}"})
    public String editTankNation(@PathVariable(required = false) Long id, Model model){
        if(id == null || id <= 0){
            model.addAttribute("fullNationDTO", new FullNationDTO());
        }
        else {
            model.addAttribute("nationId", id);
            model.addAttribute("fullNationDTO", new FullNationDTO(nationService.findNation(id)));
        }

        return "nation-tank-edit";
    }

    @PostMapping(value = {"", "/{id}"})
    public String saveNation(@PathVariable(required = false) Long id,
                             @ModelAttribute @Valid SimpleNationDTO simpleNationDTO,
                             BindingResult bindingResult,
                             Model model){
        if(bindingResult.hasErrors()){
            model.addAttribute("errors", bindingResult.getAllErrors());
            return "nation-edit";
        }

        if(id == null || id <= 0){
            nationService.addNation(simpleNationDTO.getNation());
        } else {
            nationService.updateNation(id, simpleNationDTO.getNation(), null);
        }

        return "redirect:/nation";
    }

    @PostMapping("/delete/{id}")
    public String deleteNation(@PathVariable Long id){
        nationService.deleteNation(id);
        return "redirect:/nation";
    }
}
