package fyloz.trial.ColorRecipesExplorer.core.io;

import fyloz.trial.ColorRecipesExplorer.model.Recipe;
import fyloz.trial.ColorRecipesExplorer.services.RecipeService;

import java.util.List;
import java.util.stream.Collectors;

public class ImageHandler extends FileHandler {

    private Recipe recipe;
    private int index = 0;
    private RecipeService recipeService;

    public ImageHandler(Recipe recipe, RecipeService recipeService) {
        super(String.format("%s_%s", recipe.getRecipeID(), recipe.getRecipeCode()), FileContext.IMAGE, FileExtension.JPEG);

        this.recipe = recipe;
        this.recipeService = recipeService;
    }

    public ImageHandler(String name, RecipeService recipeService) {
        super(name.replace(".jpeg", ""), FileContext.IMAGE, FileExtension.JPEG);

        String[] nameParts = name.split("-");
        index = Integer.parseInt(nameParts[1].replace(".jpeg", ""));
    }

    @Override
    public boolean createFile() {
        if (recipe != null) {
            List<String> existingImages = recipeService.getImageFiles(recipe);

            if (existingImages != null) {
                List<Integer> existingImagesIndexes = existingImages.stream().map(n -> Integer.parseInt(n.replace(name + "-", "").replace(".jpeg", ""))).collect(Collectors.toList());

                while (existingImagesIndexes.contains(index)) {
                    index++;
                }
            }

            setName(String.format("%s-%s", getName(), index));
            return super.createFile();
        }

        logger.warn("Tentative de créer une image sans recette");
        return false;
    }
}
