import {emit} from './event'
import myLogger from './logger'

let domainIp = '192.168.10.';

const domainPort = "7788";

const socket = {};

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

socket.getIp1 = ()=>{
    if(!getIpING) {
        getIpING = true;
        for(let j = 0; j< 255 ; j ++){
            let wsUrl = `ws://${domainIp}${j}:${domainPort}/notify?from=plant`;
            let ws1 = new WebSocket(wsUrl);
            ws1.onopen = function()
            {
                if(currentIpIndex === 255){
                    currentIpIndex = j;
                    // ws1.close();
                }else{
                    ws1.close();
                }

            };
            ws1.onmessage = (evt)=>{
                if(currentIpIndex !== 255){
                    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++;
                if(totalCount >= 255){
                    totalCount = 0;
                    currentIpIndex = 255;
                    getIpING = false;
                    socket.getIp1();
                }
            }
        }
    }

}


socket.getTestIp = (ip) => {
    let wsUrl = `ws://${domainIp}${ip}:${domainPort}/notify?from=plant`;
    let ws1 = new WebSocket(wsUrl);
    ws1.onopen = function()
    {
        if(currentIpIndex === 255){
            currentIpIndex = ip;
            // ws1.close();
        }else{
            ws1.close();
        }

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

    };
}


const getError = ()=>{
    getClose();
}

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



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

    let wsUrl = `ws://${domainIp}${ip}:${domainPort}/notify?from=plant&storeId=${storeid}`;
    if("WebSocket" in window && !ws && ip && storeid && (currentIpIndex === 255 || from)){
        ws = new WebSocket(wsUrl);

        ws.onopen = function()
        {
            // Web Socket 已连接上，使用 send() 方法发送数据
            // ws.send("发送数据");
            currentIpIndex = ip;
            storeId = storeid;
            getIpING = false;
            myLogger.saveDomain(domainIp+ip);
            emit(CONFIG.socketType.GETSTOREINFO,{ip:domainIp+ip,storeId:storeid})
        };

        ws.onmessage = function (evt)
        {
            if(evt.data === "ping"){
                let o = {
                    type : 'PONG'
                };
                ws.send(JSON.stringify(o));
            }else{
                var received_msg = JSON.parse(evt.data); //String
                emit(CONFIG.socketType.GETSOCKETMSG,received_msg);
            }

        };

        ws.onclose = function(err)
        {
            // 关闭 websocket
            myLogger.error("socket close & getIpING",err,getIpING);
            emit(CONFIG.socketType.SOCKETERROR,"");
            getClose();
        };
        ws.onerror = function (err) {
            myLogger.error("socket error & getIpING",err,getIpING);
            emit(CONFIG.socketType.SOCKETERROR,"");
            getError();
        }


    }
};


socket.sendMsg = (msg) => {
    if(ws){
        try{
            ws.send(msg);
        }catch (e) {
        }

    }
}

const closeSocket = ()=>{
    if(ws){
        try{
            ws.close();
            ws = null;
        }catch (e) {
        }
    }
}
module.exports = socket;