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

import dev.fyloz.trial.colorrecipesexplorer.web.response.ModelResponseBuilder;
import dev.fyloz.trial.colorrecipesexplorer.web.response.ResponseDataType;
import dev.fyloz.trial.colorrecipesexplorer.service.PasswordService;
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.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

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

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

    private RecipeService recipeService;

    @Autowired
    public IndexController(RecipeService recipeService) {
        this.recipeService = recipeService;
    }

    /**
     * Affiche la page d'acceuil.
     *
     * @return La page à afficher.
     */
    @GetMapping({INDEX, "/"})
    public ModelAndView getPage() {
        return new ModelResponseBuilder(INDEX)
                .addResponseData(ResponseDataType.RECIPE_MAP, recipeService.getAllMappedByCompany())
                .build();
    }

    /**
     * Valide un mot de passe reçu dans une requête HTTP POST, dans le champ "password".
     *
     * @param data Corps de la requête HTTP
     * @return Si le mot de passe est valide.
     */
    @PostMapping(value = PASSWORD_VALIDATION, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public boolean validatePassword(@RequestBody Map<String, Object> data) {
        return PasswordService.isValid((String) data.get("password"));
    }
}
