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

import dev.fyloz.trial.colorrecipesexplorer.exception.CannotDeleteDefaultMaterialTypeException;
import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityLinkedException;
import dev.fyloz.trial.colorrecipesexplorer.exception.model.EntityNotFoundException;
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 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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_MATERIAL_TYPE;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_MATERIAL_TYPE_SPECIFIC;

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

    private MaterialTypeJavaService materialTypeService;

    @Autowired

    public MaterialTypeRemoverController(MaterialTypeJavaService materialTypeService) {
        this.materialTypeService = materialTypeService;
    }

    @GetMapping(REMOVER_MATERIAL_TYPE)
    public ModelAndView getPage(ModelAndView model) {
        return new ModelResponseBuilder(model)
                .withView(REMOVER_MATERIAL_TYPE)
                .addResponseData(ResponseDataType.MATERIAL_TYPES, materialTypeService.getAllNotDefault())
                .build();
    }

    @PostMapping(REMOVER_MATERIAL_TYPE_SPECIFIC)
    public ModelAndView removeMaterialType(@PathVariable Long id) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder();

        try {
            MaterialType materialType = materialTypeService.getById(id);
            materialTypeService.delete(materialType);
            modelResponseBuilder.addResponseCode(ResponseCode.SUCCESS_DELETING_MATERIAL_TYPE, materialType.getName());
        } catch (EntityLinkedException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.MATERIAL_TYPE_LINKED, materialTypeService.getById(id).getName());
        } catch (EntityNotFoundException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.MATERIAL_TYPE_NOT_FOUND, id);
        } catch (CannotDeleteDefaultMaterialTypeException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.CANNOT_REMOVE_DEFAULT_MATERIAL_TYPE);
        }

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