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.LevelDTO;
import premium_store.controller.DTO.SimpleNationDTO;
import premium_store.service.NationService;
import premium_store.service.TankLevelService;

import javax.validation.Valid;

@Controller
@RequestMapping("/level")
public class LevelMvcController {
    private final TankLevelService levelService;

    public LevelMvcController(TankLevelService levelService){
        this.levelService = levelService;
    }

    @GetMapping
    public String getLevels(Model model){
        model.addAttribute("levels",
                levelService.findAllLevels().stream()
                        .map(LevelDTO::new)
                        .toList());
        return "level";
    }

    @GetMapping(value = {"/edit", "/edit/{id}"})
    public String editLevel(@PathVariable(required = false) Long id, Model model){
        if(id == null || id <= 0){
            model.addAttribute("levelDTO", new LevelDTO());
        }
        else {
            model.addAttribute("levelId", id);
            model.addAttribute("levelDTO", new LevelDTO(levelService.findLevel(id)));
        }

        return "level-edit";
    }

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

        if(id == null || id <= 0){
            levelService.addLevel(levelDTO.getLevel());
        } else {
            levelService.updateLevel(id, levelDTO.getLevel());
        }

        return "redirect:/level";
    }

    @PostMapping("/delete/{id}")
    public String deleteLevel(@PathVariable Long id){
        levelService.deleteLevel(id);
        return "redirect:/level";
    }
}