import {api} from "./api";
import {requests} from "../../requests";
import {sortList} from "../../components/cocktails/sortingList";
import {getComparator} from "../../components/core/getComparator";

class CocktailClient {
    emptyCocktailForEditPage = {
        id: null,
        name: "",
        alcoholic: "",
        category: "",
        components: "",
        glass: "",
        image: "",
        instructions: "",
        isAllowed: false,
        rating: {
            rating: 0,
            favourite: false
        },
        receipt: [],
        tags: "",
        video: ""
    }

    getMenu(setRows, setIsNew, setPage, setLoad, setIsEnd, isNew, rows, page, size, filter, createError) {
        setLoad(true);

        const request = {
            ...filter,
            sort: sortList.find((s) => s.name === filter.sorting).id,
            page: page + 1,
            size: size,
            notHaveCount: Array.isArray(filter.iCount) ? null : filter.iCount
        }

        api().post(requests.cocktails.menu, request)
            .then((r) => {
                if (r.data.length === 0) {
                    if (isNew) {
                        setRows([]);
                    }
                    setIsEnd(true);
                    setLoad(false);
                    return;
                }
                const cocktails = isNew ? r.data : rows.concat(r.data);
                setRows(cocktails);
                setIsNew(false);
                setPage(page + 1);
                setLoad(false);
            })
            .catch((r) => {
                setLoad(false);
                createError("Ошибка загрузки данных от сервера Status:" + r.code)
            })
    }

    async getCocktailByIngredient(ingredient, setCocktails) {
        if(!ingredient) {
            return
        }
        api().get(requests.cocktails.byIngredient + ingredient.id)
            .then((r) => setCocktails(r.data))
    }

    getCocktailsForCalcPage(load,setLoad, setCocktails, setCocktailMap, createError) {
        if (load) {
            return;
        }
        api().get(requests.cocktails.calc)
            .then((r) => {
                const data = r.data;
                if (data.length === 0) {
                    setLoad(false);
                    return;
                }
                setCocktails(data);
                let map = {};
                data.forEach((d) => {
                    map = {
                        ...map,
                        [d.id]: 1
                    }
                })
                setCocktailMap(map);
                setLoad(true);
            })
            .catch((r) => {
                setLoad(true);
                createError("Ошибка загрузки данных от сервера Status:" + r.code)
            })
    }

    savePhoto(event, changeCocktailValue, getError) {
        const file = event.target.files[0];
        let formData = new FormData();
        formData.append('file', file);
        api().post(requests.cocktails.photo, formData)
            .then((r) => changeCocktailValue("image", r.data))
            .catch(() => getError())
    }

    deleteCocktailFromEdit(setCocktails, setCocktail, createError, cocktails, cocktail, emptyCocktail) {
        api().delete(requests.cocktails.cocktail + cocktail.id)
            .then(() => {
                setCocktails(cocktails.filter((r) => r.id !== cocktail.id))
                setCocktail(emptyCocktail);
            })
            .catch(() => createError("Ошибка удаления коктейля"))
    }

    deleteCocktail(id, rows, setRows, createSuccess, createError) {
        api().delete(requests.cocktails.cocktail + id)
            .then(() => {
                setRows(rows.filter((r) => r.id !== id))
                createSuccess("Коктейль удален")
            })
            .catch(() => createError("Ошибка удаления коктейля"))
    }

    async hiddenCocktail(id) {
        return api().post(requests.cocktails.hide + id);
    }

    saveChangeCocktail (cocktail, createError, createSuccess) {
        api().patch(requests.cocktails.basic, cocktail)
            .then((r) => {
                if (!r.data.error) {
                    createSuccess("Сохранено")
                    return;
                }
                createError("Ошибка на сервере: " + r.data.error)
            })
            .catch(() => createError("Неизвестная ошибка"))
    }

    getOneCocktail (selected, setCocktail, getError, emptyCocktail) {
        if (!selected) {
            setCocktail(emptyCocktail);
            return;
        }
        api().get(requests.cocktails.cocktail + selected)
            .then((r) => {
                setCocktail(r.data)
            })
            .catch(() => getError());
    }

    getSimpleList(setCocktails, setSelected, setLoading, createError, currentId) {
        api().get(requests.cocktails.simple)
            .then((r) => {
                const arr = r.data.sort(getComparator("asc", "name"));
                setCocktails(arr)

                if (!currentId) {
                    setLoading(false);
                    return;
                }
                const currentCocktail = arr.find((r) => r.id === (currentId * 1));
                if (!currentCocktail) {
                    setLoading(false);
                    return;
                }
                setSelected(currentCocktail.id);
                setLoading(false);
            })
            .catch(() => createError("Ошибка получения данных"))
    }

    getCocktailForModal (row, setLoading, setCocktail, closeCocktail, getError) {
        setLoading(true)
        if (!row) {
            setLoading(false)
            return;
        }
        api().get(requests.cocktails.modal + row)
            .then((r) => {
                setCocktail(r.data)
                setLoading(false)
            })
            .catch(() => {
                getError();
                setLoading(false)
                closeCocktail();
            })
    }

    changeFavourite(value, id, newState, setRows, createSuccess, createError) {
        const url = `${requests.cocktails.favourite}${id}`;
        const request = value ? api().put(url) : api().delete(url);

        request
            .then(() => {
                setRows(newState);
                createSuccess("Спасибо за оценку!")
            }).catch(() => createError("Ошибка сохранения"))
    }

    changeRating(id, newState, value, setRows, createSuccess, createError) {
        api().post(`${requests.cocktails.rating}${id}&rating=${value}`)
            .then(() => {
                setRows(newState);
                createSuccess("Спасибо за оценку!")
            }).catch(() => createError("Ошибка сохранения"))
    }

    drinkCocktail(id, createSuccess, createError) {
        api().post(`${requests.cocktails.drink}/${id}`)
            .then(() => createSuccess("Бон аппетит"))
            .catch(() => createError("Ошибка отметки коктейля"))
    }

}

export const cocktailClient = new CocktailClient();