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

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)=>{
    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 + ':8088/testIp';
            fetch( url ,{
                // credentials : 'include',
                method : 'POST',
                mode : 'cors',
                body : {}
            }).then(checkStatus)
                .then(parseJson)
                .then((data) => {
                    dispatch(saveIp(domainIp + i + ':8088'))
                })
                .catch((err) =>{
                    failTotal++;
                    if(failTotal >= totalIndex + initIndex){
                        initIndex = totalIndex + initIndex > 255 ? 1 : totalIndex + initIndex;
                        dispatch(getIp())
                    }
                });
        }
    })
};
export {getIp}
