package ru.kayashov.bar.service.integration.cocktail;

import org.springframework.http.HttpEntity;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Service;
import ru.kayashov.bar.model.Cocktail;
import ru.kayashov.bar.model.Ingredient;
import ru.kayashov.bar.model.api.cocktail.Cocktails;
import ru.kayashov.bar.model.api.cocktail.Ingredients;
import ru.kayashov.bar.service.RestUtil;

import java.util.Collections;
import java.util.List;

@Service
public class CocktailApiService {

    public Ingredient getIngredientById(long id) {
        String url = "https://www.thecocktaildb.com/api/json/v1/1/lookup.php?iid=";
        return RestUtil.sendRequest(Ingredients.class,
                        RequestEntity.get(url + id).build())
                .map(HttpEntity::getBody)
                .map(Ingredients::getIngredients)
                .map(i -> i.get(0))
                .orElse(null);
    }

    public Cocktail getCocktailById(long id) {
        String url = "https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=";
        return RestUtil.sendRequest(Cocktails.class,
                        RequestEntity.get(url + id).build())
                .map(HttpEntity::getBody)
                .map(Cocktails::getDrinks)
                .map(i -> i.get(0))
                .orElse(null);
    }

    public List<Cocktail> getCocktailByLiteral(String literal) {
        String url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?f=";
        return RestUtil.sendRequest(Cocktails.class,
                        RequestEntity.get(url + literal).build())
                .map(HttpEntity::getBody)
                .map(Cocktails::getDrinks)
                .orElse(Collections.emptyList());
    }

}
