package fyloz.trial.ColorRecipesExplorer.web.controller.creators;

import fyloz.trial.ColorRecipesExplorer.model.MaterialType;
import fyloz.trial.ColorRecipesExplorer.services.MaterialTypeService;
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.PostMapping;

import javax.validation.Valid;

import static fyloz.trial.ColorRecipesExplorer.web.PagesPaths.CREATOR_MATERIAL_TYPE;
import static fyloz.trial.ColorRecipesExplorer.web.PagesPaths.INDEX;
import static fyloz.trial.ColorRecipesExplorer.web.StringBank.*;

@Controller
public class MaterialTypeCreatorController {

    private MaterialTypeService materialTypeService;

    @Autowired
    public MaterialTypeCreatorController(MaterialTypeService materialTypeService) {
        this.materialTypeService = materialTypeService;
    }

    @GetMapping(CREATOR_MATERIAL_TYPE)
    public String showPage() {
        return CREATOR_MATERIAL_TYPE;
    }

    @PostMapping(CREATOR_MATERIAL_TYPE)
    public String create(Model model, @Valid MaterialType materialType) {
        if (materialTypeService.isValidForCreation(materialType)) {
            if (materialTypeService.save(materialType) != null) {
                return "redirect:/" + INDEX;
            } else {
                model.addAttribute(RESPONSE_ERROR, ERROR_SAVING);
            }
        } else {
            model.addAttribute(RESPONSE_ERROR, String.format(MIX_TYPE_ALREADY_USED, materialType.getMaterialTypeName()));
        }

        return showPage();
    }
}
