import fetch from 'isomorphic-fetch';
import {emit} from './event'


let domainIp = '192.168.10.';

let initIndex = 1;
let totalIndex = 255 / 5;
let failTotal = 1;
let currentIpIndex = 0;
let ws = null;
let inteval = null;
let timer = null;
let time = 60000;
let intevalTime = 30000;
let isFalse = false;

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 getIp = ()=>{
    console.log("getIp : ",initIndex)
    for(let i = initIndex; i < (totalIndex + initIndex) ; i++){
        let url = 'http://' + domainIp + i + ':9999/getmyid';
        console.log(url)
        fetch( url ,{
            // credentials : 'include',
            method : 'GET',
            mode : 'cors',
        }).then(checkStatus)
            .then(parseJson)
            .then((data) => {
                console.log("data :",data);
                if(data.storeId){
                    let wsUrl = 'ws://' + domainIp + i + ':7788/notify?from=plant&storeId='+data.storeId;
                    currentIpIndex = i;
                    init(i,data.storeId);
                }

            })
            .catch((err) =>{
                console.error("Err:",err);
                failTotal++;
                if(failTotal >= totalIndex + initIndex){
                    initIndex = totalIndex + initIndex;
                    if(initIndex > 255){
                        inteval = setTimeout(function () {
                            console.log("------");
                            window.clearTimeout(inteval);
                            inteval = null;
                            initIndex = 1;
                            failTotal = 1;
                            getIp();
                        },intevalTime)
                    }else{
                        getIp();
                    }


                }
            });
    }
};

const testIp = (ip) => {
    console.log("testIp : ",ip);

    let url = 'http://' + domainIp + ip + ':9999/getmyid';
    fetch( url ,{
        // credentials : 'include',
        method : 'GET',
        mode : 'cors',
    }).then(checkStatus)
        .then(parseJson)
        .then((data) => {
            if(data.storeId){
                window.storeId = data.storeId;
                window.localIp = domainIp + ip;

                let wsUrl = 'ws://' + domainIp + ip + ':7788/notify?from=plant&storeId='+data.storeId;
                currentIpIndex = ip;
                init(ip,data.storeId);
            }
        })
        .catch((err) =>{
            console.error("Err:",err);
            currentIpIndex = 0;
            window.clearTimeout(inteval);
            inteval = null;
            initIndex = 1;
            failTotal = 1;
            getIp()
        });
}


const init = (ip,storeid)=>{

    let wsUrl = 'ws://' + domainIp + ip + ':7788/notify?from=plant&storeId=' + storeid;
    console.log("init :" ,wsUrl);
    if("WebSocket" in window && !ws && ip && storeid){
        ws = new WebSocket(wsUrl);

        ws.onopen = function()
        {
            // Web Socket 已连接上,使用 send() 方法发送数据
            // ws.send("发送数据");
            clearInterval(timer);
            timer = null;
            window.clearTimeout(inteval);
            inteval = null;
            initIndex = 1;
            failTotal = 1;
            console.log("open");
            isFalse = false;

            emit(CONFIG.socketType.GETSTOREINFO,{ip:domainIp+ip,storeId:storeid})
        };

        ws.onmessage = function (evt)
        {
            var received_msg = JSON.parse(evt.data); //String
            console.log("数据已接收...");
            emit(CONFIG.socketType.GETSOCKETMSG,received_msg);
        };

        ws.onclose = function(err)
        {
            // 关闭 websocket
            console.log("close : ",err);
            getError();
        };
        ws.onerror = function (err) {
            console.error("error : ",err);
            getError();
        }


    }
};

const getError = ()=>{
    ws = null;
    isFalse = true;
    console.log("getError")
    if(currentIpIndex){
        testIp(currentIpIndex);
    }else{
        window.clearTimeout(inteval);
        inteval = null;
        initIndex = 1;
        failTotal = 1;
        getIp();
    }
    // if(!ws && !timer){
    //     console.log("in timer")
    //     timer = setInterval(function () {
    //         getError();
    //     },time)
    // }

}

const sendMsg = (msg) => {
    if(ws){
        try{
            ws.send(msg);
        }catch (e) {
            console.error("sendMsg error :",e)
        }

    }
}

const closeSocket = ()=>{
    if(ws){
        try{
            ws.close();
            ws = null;
        }catch (e) {
            console.error("closeSocket error :",e)
        }
    }
}

module.exports = {getIp,sendMsg,init,testIp};