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


let domainIp = '192.168.10.';

const socket = {};

let totalCount = 0;
let getIpING = false; //正在获取IP
let currentIpIndex = 255;
let ws = null;
let storeId = 0

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)=>{
    console.log("socket response ",response);
    return response.json();
};

// socket.getIp = ()=>{
//     console.log("getIp ",getIpING,currentIpIndex);
//     if(!getIpING){
//         getIpING = true;
//         for(let i = 0; i < 255 ; i ++){
//             let url = 'http://' + domainIp + i + ':9999/getmyid';
//             if(currentIpIndex === 255 && getIpING){
//                 fetch( url ,{
//                     // credentials : 'include',
//                     method : 'GET',
//                     mode : 'cors',
//                 }).then(checkStatus)
//                     .then(parseJson)
//                     .then((data) => {
//                         console.error("data :",data,currentIpIndex,i);
//                         if(data.storeId && currentIpIndex === 255){
//                             init(i,data.storeId);
//                         }
//                     })
//                     .catch((err) =>{
//                         console.error("Err:",err);
//                         totalCount++;
//                         if(totalCount >= 255){
//                             totalCount = 0;
//                             currentIpIndex = 255;
//                             getIpING = false;
//                             socket.getIp();
//                         }
//
//                     });
//             }
//
//         }
//     }
//
// };

socket.getIp1 = ()=>{
    if(!getIpING) {
        getIpING = true;
        for(let j = 0; j< 255 ; j ++){
            let wsUrl = 'ws://' + domainIp + j + ':7788/notify?from=plant';
            let ws1 = new WebSocket(wsUrl);
            ws1.onopen = function()
            {
                console.log("ok ")
                if(currentIpIndex === 255){
                    console.log("ip ",j);
                    currentIpIndex = j;
                    // ws1.close();
                }else{
                    ws1.close();
                }

            };
            ws1.onmessage = (evt)=>{
                if(currentIpIndex !== 255){
                    console.log('onmessage ',currentIpIndex,evt.data);
                    let info = JSON.parse(evt.data);
                    if(info.type === 'GET_STORE_ID' && info.data){
                        ws1.close();
                        init(currentIpIndex,info.data,true);
                    }
                }

            };
            ws1.onerror = function (err) {
                totalCount++;
                console.log("totalCount ",totalCount)
                if(totalCount >= 255){
                    console.log("totalCount inin")
                    totalCount = 0;
                    currentIpIndex = 255;
                    getIpING = false;
                    socket.getIp1();
                }
            }
        }
    }

}

// socket.getStoreIdByIp = (ip) => {
//     let url = 'http://' + domainIp + ip + ':9999/getmyid';
//     fetch( url ,{
//         // credentials : 'include',
//         method : 'GET',
//         mode : 'cors',
//     }).then(checkStatus)
//         .then(parseJson)
//         .then((data) => {
//             console.log("socket data ",data);
//             if(data.storeId){
//                 init(ip,data.storeId,true);
//             }
//         })
//         .catch((err) =>{
//             console.error("Err:",err);
//             if(!getIpING){
//                 console.log("getStoreIdByIp=======")
//                 currentIpIndex = 255;
//                 totalCount = 0;
//                 socket.getIp1();
//             }
//         });
// }


const getError = ()=>{
    console.error("socket error");
    getClose();
}

const  getClose = ()=>{
    console.error("socket close ",currentIpIndex);
    //如果有currentIp就没有必要再次循环
    ws = null;
    if(!getIpING){
        console.log("socket close========");
        currentIpIndex = 255;
        totalCount = 0;
        storeId = 0;
        socket.getIp1();
    }
}



const init = (ip,storeid,from = false)=>{

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

        ws.onopen = function()
        {
            // Web Socket 已连接上，使用 send() 方法发送数据
            // ws.send("发送数据");
            currentIpIndex = ip;
            storeId = storeid;
            getIpING = false;
            console.log("open");
            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);
            emit(CONFIG.socketType.SOCKETERROR,"");
            getClose();
        };
        ws.onerror = function (err) {
            console.error("error : ",err);
            emit(CONFIG.socketType.SOCKETERROR,"");
            getError();
        }


    }
};


socket.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 = socket;