import fetch from 'isomorphic-fetch'
import actionType from '../actiontype/getIp'
let domain = 'http://192.168.10.100:7788';

let domainIp = '192.168.10.';

let initIndex = 1;
let key = 3;
let totalIndex = 255 / 5;
let onceIndex = totalIndex / key;
let failTotal = 1;


const saveIp = (data)=>{
    return{
        type : actionType.SAVEIP,
        data
    }
};

const checkStatus = (response)=>{
    console.log("===========")
    console.log(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 testIp = ()=>{

};


const getIp = ()=>{
    return (dispatch =>{
        for(let i = initIndex; i < (totalIndex + initIndex) ; i++){
            let url = 'http://' + domainIp + i + ':7788/testIp';
            fetch( url ,{
                // credentials : 'include',
                method : 'POST',
                mode : 'cors',
                body : {}
            }).then(checkStatus)
                .then(parseJson)
                .then((data) => {
                    console.log("data :",data);
                    dispatch(saveIp(domainIp + i + ':7788'))
                })
                .catch((err) =>{
                    console.error("Err:",err);
                    failTotal++;
                    if(failTotal >= totalIndex + initIndex){
                        initIndex = totalIndex + initIndex > 255 ? 1 : totalIndex + initIndex;
                        dispatch(getIp())
                    }
                });
        }
    })
};
export {getIp}