package dev.fyloz.trial.colorrecipesexplorer.web.controller.thymeleaf.creators;

import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityAlreadyExistsException;
import dev.fyloz.trial.colorrecipesexplorer.exception.model.ModelException;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ModelResponseBuilder;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseCode;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseDataType;
import dev.fyloz.trial.colorrecipesexplorer.model.MaterialType;
import dev.fyloz.trial.colorrecipesexplorer.service.model.MaterialTypeJavaService;
import dev.fyloz.trial.colorrecipesexplorer.utils.ControllerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.CREATOR_MATERIAL_TYPE;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.INDEX;

@Controller
@Profile("thymeleaf")
public class MaterialTypeCreatorController {

    private MaterialTypeJavaService materialTypeService;

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

    @GetMapping(CREATOR_MATERIAL_TYPE)
    public ModelAndView getPage(ModelAndView model, MaterialType materialType) {
        return new ModelResponseBuilder(model)
                .withView(CREATOR_MATERIAL_TYPE)
                .addResponseData(ResponseDataType.MATERIAL_TYPE, materialType == null ? new MaterialType() : materialType)
                .build();
    }

    @PostMapping(CREATOR_MATERIAL_TYPE)
    public ModelAndView createMaterialType(@Valid MaterialType materialType) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder(ControllerUtils.redirect(INDEX));

        try {
            materialTypeService.save(materialType);
            return getPage(
                    modelResponseBuilder.addResponseCode(ResponseCode.SUCCESS_SAVING_MATERIAL_TYPE, materialType.getName()).build(),
                    null
            );
        } catch (EntityAlreadyExistsException ex) {
            if (ex.getIdentifierType() == ModelException.IdentifierType.NAME) {
                modelResponseBuilder.addResponseCode(ResponseCode.MATERIAL_TYPE_ALREADY_EXIST, materialType.getName());
            } else {
                modelResponseBuilder.addResponseCode(ResponseCode.MATERIAL_TYPE_ALREADY_EXIST_PREFIX, materialType.getPrefix());
            }
        }

        return getPage(modelResponseBuilder.build(), materialType);
    }
}
