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

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.Material;
import dev.fyloz.trial.colorrecipesexplorer.service.model.MaterialJavaService;
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 java.util.stream.Collectors;

import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_MATERIAL;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.REMOVER_MATERIAL_SPECIFIC;

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

    private MaterialJavaService materialService;

    @Autowired
    public MaterialRemoverController(MaterialJavaService materialService) {
        this.materialService = materialService;
    }

    @GetMapping(REMOVER_MATERIAL)
    public ModelAndView getPage(ModelAndView model) {
        return new ModelResponseBuilder(model)
                .withView(REMOVER_MATERIAL)
                .addResponseData(ResponseDataType.MATERIALS, materialService.getAll().stream().filter(m -> !m.isMixType()).collect(Collectors.toList()))
                .build();
    }

    @PostMapping(REMOVER_MATERIAL_SPECIFIC)
    public ModelAndView removeMaterial(@PathVariable Long id) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder();

        try {
            Material material = materialService.getById(id);
            materialService.delete(material);
            modelResponseBuilder.addResponseCode(ResponseCode.SUCCESS_DELETING_MATERIAL, material.getName());
        } catch (EntityLinkedException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.MATERIAL_LINKED, materialService.getById(id).getName());
        } catch (EntityNotFoundException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.MATERIAL_NOT_FOUND, id);
        }

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