package fyloz.trial.ColorRecipesExplorer.web.controller;

import fyloz.trial.ColorRecipesExplorer.PasswordValidator;
import fyloz.trial.ColorRecipesExplorer.model.Company;
import fyloz.trial.ColorRecipesExplorer.model.Recipe;
import fyloz.trial.ColorRecipesExplorer.services.CompanyService;
import fyloz.trial.ColorRecipesExplorer.services.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static fyloz.trial.ColorRecipesExplorer.web.PagesPaths.INDEX;
import static fyloz.trial.ColorRecipesExplorer.web.PagesPaths.PASSWORD_VALIDATION;
import static fyloz.trial.ColorRecipesExplorer.web.StringBank.RECIPES;

@Controller
public class IndexController {

    private CompanyService companyService;
    private RecipeService recipeService;

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

    /**
     * Affiche la page d'acceuil.
     *
     * @param model Le Model injecté par Thymeleaf
     * @return La page à afficher.
     */
    @GetMapping({INDEX, "/"})
    public String showPage(Model model) {
        List<Company> companies = companyService.getAll();
        Map<Company, List<Recipe>> recipes = new HashMap<>();

        for (Company company : companies) {
            recipes.put(company, recipeService.getByCompany(company));
        }

        model.addAttribute(RECIPES, recipes);

        return INDEX;
    }

    /**
     * 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 PasswordValidator.isValid((String) data.get("password"));
    }
}
