import {useEffect, useState} from "react";
import {apiAxios} from "../utils/Tools.js";

function stdAction(promise, setData, setErrors, setLoading = null, loadingLevel = 1) {
    if (setLoading)
        setLoading(loadingLevel)

    promise.then(data => {
        setData(data.data)
    }).catch(e => {
        setErrors(e.response)
    }).finally(() => {
        if (setLoading)
            setLoading(0)
    })
}

export function useFetch(url, setLoading = null, loadingLevel = 1, config = {}) {
    const [data, setData] = useState(null)
    const [error, setErrors] = useState(null)

    const refresh = (url) => {
        stdAction(apiAxios.get(url, config), setData, setErrors, setLoading, loadingLevel)
    }

    useEffect(() => {
        if (url !== null)
            refresh(url)
    }, []);

    return {
        data, error, refresh
    }
}

export function useFetchPut(url, dataRequest, setLoading = null, loadingLevel = 1, config = {}) {
    const [data, setData] = useState(null)
    const [error, setErrors] = useState(null)

    useEffect(() => {
        stdAction(apiAxios.put(url, dataRequest, config), setData, setErrors, setLoading, loadingLevel)
    }, []);

    return {
        data, error
    }
}
