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

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.Recipe;
import dev.fyloz.trial.colorrecipesexplorer.service.model.CompanyService;
import dev.fyloz.trial.colorrecipesexplorer.service.model.RecipeService;
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_RECIPE;
import static dev.fyloz.trial.colorrecipesexplorer.web.WebsitePaths.EDITOR_RECIPE_SPECIFIC;

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

    private RecipeService recipeService;
    private CompanyService companyService;

    @Autowired
    public RecipeCreatorController(RecipeService recipeService, CompanyService companyService) {
        this.recipeService = recipeService;
        this.companyService = companyService;
    }

    @GetMapping(CREATOR_RECIPE)
    public ModelAndView getPage(ModelAndView model, Recipe recipe) {
        ModelResponseBuilder responseBuilder = new ModelResponseBuilder(model)
                .withView(CREATOR_RECIPE)
                .addResponseData(ResponseDataType.COMPANIES, companyService.getAll())
                .addResponseData(ResponseDataType.RECIPE, recipe == null ? new Recipe() : recipe);

        if (companyService.getAll().isEmpty()) {
            responseBuilder.addResponseCode(ResponseCode.NO_COMPANY)
                    .addResponseData(ResponseDataType.BLOCK_BUTTON, true);
        }

        return responseBuilder.build();
    }

    @PostMapping(CREATOR_RECIPE)
    public ModelAndView createRecipe(@Valid Recipe recipe) {
        ModelResponseBuilder modelResponseBuilder = new ModelResponseBuilder();

        long id = recipeService.save(recipe).getId();

        return modelResponseBuilder.withRedirect(EDITOR_RECIPE_SPECIFIC, id).build();
    }
}
