import { useQuery, useMutation, useQueryClient } from "react-query";
import { fetch_ } from "./request-utils";
import {useConfig} from "../ConfigProvider";


export const usePaths = (parent_id) => {
    const queryClient = useQueryClient();
    const config = useConfig();
    return useQuery(
        ["paths", parent_id],
        () => fetch_(`${config.BACKEND_HOST}/api/path/parent/${parent_id}`),
        {
            enabled: !!parent_id,
            onSuccess: (data) => {
                if(data) {
                    for (const pth of data)
                    {
                        queryClient.setQueryData(["path", pth.id], pth);
                    }
                }
            }
        }
    );
}


export const usePath = (id) => {
    const config = useConfig();
    const queryClient = useQueryClient();
    const cachedData = queryClient.getQueryData(["path", id]);


    return useQuery(
        ["path", id],
        () => fetch_(`${config.BACKEND_HOST}/api/path/${id}`),
        {
            enabled: !!id,
            onSuccess: (data) => {
                console.log(`path ${id} - ${cachedData}` );
            }
        }
    );
};

export const useCreatePath = () => {
    const config = useConfig();
    const queryClient = useQueryClient();

    return useMutation(
        (data) => fetch_(`${config.BACKEND_HOST}/api/path/`, {
            method: "POST",
            body: JSON.stringify(data),
        }),
        {
            onSuccess: (res, variables) => {
                console.log(JSON.stringify(variables));
                queryClient.invalidateQueries(["paths", variables.parent_id]);
            },
        }
    );
};

export const useUpdatePath = () => {
    const config = useConfig();
    const queryClient = useQueryClient();

    return useMutation(
        ({ id, data }) => fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
            method: "PATCH",
            body: JSON.stringify(data),
        }),
        {
            onSuccess: (res, variables) => {
                queryClient.invalidateQueries(["paths", res.parent_id]);
                queryClient.invalidateQueries(["path", variables.data.id]);
            },
        }
    );
};

export const useDeletePath = () => {
    const config = useConfig();
    const queryClient = useQueryClient();

    return useMutation(
        (id) => fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
            method: "DELETE",
        }),
        {
            onSuccess: () => {
                queryClient.invalidateQueries("paths");
            },
        }
    );
};