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

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

//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 post = ({url, params, onSuccess, onFail, onError}) =>{
    axios.post(url,params,
        {
            headers: {
                "Content-Type":"application/json"
            }
        }).then(
        (response)=>{onResponse(response, onSuccess, onFail);}
    ).catch(error => {
        return handleError(error,onError);
    });
};

export const fileDownload = ({fileId, skey, filename, onError}) =>{
    axios.get( FILE_DOWN_GET+"/"+fileId+"/"+skey+"/"+filename,
        {
            responseType: 'blob',
        }
    ).then(
        (response)=>{
            const url = URL.createObjectURL(response.data);
            const a = document.createElement('a');
            a.href = url;
            a.setAttribute("download", filename);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
    ).catch(error => {
        return handleError(error,onError);
    });
};

export const fileUpload = ({ refType, refId, file,refCode, onSuccess, onFail, onError}) =>{
    var formData = new FormData();
        formData.append("multipartFile", file);
        formData.append("refType", refType);
        formData.append("refId", refId);
        if(refCode){
            formData.append("refCode", refCode);
        }
        console.log(formData)
        axios.post(FILE_UP_POST,formData,{
            headers: {
                "Content-Type":"multipart/form-data"
            }
        }).then(
            (response)=>{
                onResponse(response,onSuccess,onFail);
            }
        ).catch(error => { return handleError(error, 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;
    }
}