import fetch from 'isomorphic-fetch';
import actionTypes from '../actiontype/refreshImg'
const domain = ENV.domain;
const refreshImg = (data)=>{
    return{
        type:actionTypes.REFRESHIMG,
        data
    }
};

const checkStatus = (response)=>{
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
};

const parseJson = (response)=>{
    return response.json();
};


const getRefreshImg = (errorId,type)=>{
    return(dispatch)=>{
        let bodyData = Object.assign({},{errorId,type})
        fetch(domain + 'flush_image.action',{
            credentials : 'include',
            method : 'POST',
            mode : 'cors',
            headers: {
                'content-type':'application/json;charset=UTF-8',
            },
            body: JSON.stringify(bodyData)

        }).then((response)=>response.json())
            .then(json=>{
                if(json.meta.success && json.data){
                    let data = {
                        errorId,
                        type,
                        files : json.data.files ? json.data.files : []
                    };
                    dispatch(refreshImg(data))
                }
            }).catch(e=>{console.error(e)})
    }
};

const deleteImg = (errorId,type,fileId)=>{
    return(dispatch)=>{
        let bodyData = Object.assign({},{errorId,type,fileId})
        fetch(domain + 'delete_image_error.action',{
            credentials : 'include',
            method : 'POST',
            mode : 'cors',
            headers: {
                'content-type':'application/json;charset=UTF-8',
            },
            body: JSON.stringify(bodyData)
        }).then(checkStatus)
            .then(parseJson)
            .then((data) => {
                if(data.meta.success){
                    dispatch(getRefreshImg(errorId,type))
                }
            })
            .catch((err) =>{
                console.error("Err:",err);
            });
    }

}

const emptyImg = ()=>{
    return {
        type:actionTypes.EMPTYIMG
    }
}

export {getRefreshImg,deleteImg,emptyImg}

