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

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.service.files.MarkdownFilesService;
import dev.fyloz.trial.colorrecipesexplorer.service.model.MixService;
import dev.fyloz.trial.colorrecipesexplorer.service.model.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import static dev.fyloz.trial.colorrecipesexplorer.web.StringBank.MATERIALS;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.*;

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

    private MixService mixService;
    private RecipeService recipeService;
    private MarkdownFilesService markdownService;

    @Autowired
    public OthersController(MixService mixService, RecipeService recipeService, MarkdownFilesService markdownService) {
        this.mixService = mixService;
        this.recipeService = recipeService;
        this.markdownService = markdownService;
    }

    @GetMapping(CLOSE_TAB)
    public ModelAndView getCloseTab() {
        return new ModelResponseBuilder(CLOSE_TAB).build();
    }

    @GetMapping(MATERIAL_SELECTOR_MIX)
    public ModelAndView getMaterialSelectorFragment(@PathVariable Long recipeId, @PathVariable Long mixId) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder(MATERIAL_SELECTOR_FRAGMENT);

        try {
            modelResponseBuilder.addAttribute(MATERIALS, mixService.getAvailableMaterialsForMixId(recipeService.getById(recipeId), mixId));
        } catch (EntityNotFoundException ex) {
            modelResponseBuilder.addResponseCode(ResponseCode.RECIPE_NOT_FOUND, recipeId);
        }

        return modelResponseBuilder.build();
    }

    @GetMapping(value = UPDATES)
    public ModelAndView getUpdatesPage() {
        return new ModelResponseBuilder(UPDATES).build();
    }

    @GetMapping(value = UPDATES_GET, produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public ResponseEntity<String> getUpdates() {
        return new ResponseEntity<>(markdownService.render("updates.md"), HttpStatus.OK);
    }
}
