import axios from "axios";
import { FILE_UP_POST, FILE_DOWN_GET } from "../utils/ApiPathConst";
import qs from 'qs';

export const get = ({ url, params, onSuccess, onFail, onError, onFinally }) => {
    axios.get(url, {
        params,
        paramsSerializer: (p) => qs.stringify(p, { arrayFormat: 'repeat' }) // <-- FIX
    }).then(
        (response) => { onResponse(response, onSuccess, onFail); }
    ).catch((error) => {
        return handleError(error, onError);
    }).finally(() => {
        if (typeof onFinally === 'function') {
            onFinally();
        }
    });
};

//TODO
export const put = ({ url, params, onSuccess, onFail, onError }) => {
    axios.put(url, params).then(
        (response) => { onResponse(response, onSuccess, onFail); }
    ).catch(error => {
        return handleError(error, onError);
    });
};

export const patch = ({ url, params, onSuccess, onFail, onError }) => {
    axios.patch(url, params).then(
        (response) => { onResponse(response, onSuccess, onFail); }
    ).catch(error => {
        return handleError(error, onError);
    });
};

export const post = ({ url, params, onSuccess, onFail, onError, headers }) => {
    headers = headers ? headers : {
        "Content-Type": "application/json"
    };

    axios.post(url, params,
        {
            headers: headers
        }).then(
            (response) => { onResponse(response, onSuccess, onFail); }
        ).catch(error => {
            return handleError(error, onError);
        });
};

export const postWithFiles = ({ url, params, files, onSuccess, onFail, onError }) => {
    var formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        const file = files[i]
        formData.append("multipartFileList", file);
    }
    if (params)
        for (var key in params) {
            if (typeof (params[key]) === 'object') {
                formData.append(key, JSON.stringify(params[key]));
            } else {
                formData.append(key, params[key]);
            }
        }

    axios.post(url, formData,
        { headers: { "Content-Type": "multipart/form-data" } })
        .then(
            (response) => { onResponse(response, onSuccess, onFail); }
        ).catch(error => {
            return handleError(error, onError);
        });
};

export const fileDownload = ({ url, fileId, skey, params, method, onResponse, onError }) => {
    if (!url) {
        url = FILE_DOWN_GET + "/" + fileId + "/" + skey
    }
    if (method == 'post') {
        axios.post(url, params,
            {
                responseType: 'blob',
                headers: {
                    "Content-Type": "application/json"
                }
            }
        ).then(
            (response) => {
                fileDownloadResponse(response, onResponse)
            }
        ).catch(error => {
            return handleError(error, onError);
        });

    } else {
        axios.get(url,
            {
                responseType: 'blob',
                params: params
            }
        ).then(
            (response) => {
                fileDownloadResponse(response, onResponse)
            }
        ).catch(error => {
            return handleError(error, onError);
        });
    }
};

const fileDownloadResponse = (response, onResponse) => {
    const cd = response.headers?.['content-disposition'];
    const fn = cd?.split('filename=')[1]?.replaceAll('"','')?.trim() || 'export.xlsx';

    const url = URL.createObjectURL(response.data);
    const a = document.createElement('a');
    a.href = url;
    a.download = fn;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    onResponse?.();
};

export const fileUpload = ({ refType, refId, files, refCode, onSuccess, onFail, onError }) => {
    postWithFiles({
        url: FILE_UP_POST,
        params: {
            refType: refType,
            refId: refId,
            refCode: refCode
        },
        files: files,
        onSuccess: onSuccess,
        onFail: onFail,
        onError: onError
    });
};


const onResponse = (response, onSuccess, onFail) => {
    if (response.status >= 300 || response.status < 200) {
        console.log("onFail");
        if (onFail) {
            onFail(response);
        } else {
            console.log(response);
        }
        return;
    }

    if (onSuccess) {
        onSuccess(response?.data);
    }
}

const handleError = (error, onError) => {
    if (onError) {
        return onError(error);
    } else {
        // console.log(error);
        return false;
    }
}