import {emit, on , remove} from './event';
import { exactDomainIp } from '../config/config';
import myLogger from './logger'

let domainIp = CONFIG.config.domainIp;

const domainPort = CONFIG.config.domainPort;

const socket = {};

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

//断网后1min连不上，就终止连接


let beginConnectSocket = ()=>{
    // console.log("===socket===beginConnectSocket===getIpING=== ",getIpING);
    // if(!getIpING){
    //     currentIpIndex = 255;
    //     totalCount = 0;
    //     storeId = 0;
    //     socket.getIp1();
    //     socket.stopServer();
    // }
};

socket.stopServer = ()=>{
    console.log("======stopServer====== ",stopTimer);
    if(!stopTimer){
        stopTimer = setTimeout(()=>{
            clearTimeout(stopTimer);
            stopTimer = null;
            startStopServer = true;
            //告知页面走断电断网流程
            emit(CONFIG.socketType.STARTSTOPSERVER,{});
            
            console.log("===socket===STARTSTOPSERVER====== ");
           
            let that = socket.stopServer;

            on(CONFIG.socketType.STOPSTOPSERVER,that,()=>{
                console.log("===socket===STOPSTOPSERVER====== ");
                startStopServer = false;
                getIpING = false;
                beginConnectSocket();
                remove(CONFIG.socketType.STOPSTOPSERVER,that);
            });

        },1000*60*3)
    }
};


socket.getIp1 = ()=>{
    if(!getIpING) {
        getIpING = true;
        for(let j = 0; j< 255 ; j ++){
            let connectIp = `${domainIp}${j}`;
            if (exactDomainIp) {
                connectIp = exactDomainIp;
            }
            let wsUrl = `ws://${connectIp}:${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();
                        if(!startStopServer){
                            //非断电断网情况就连接
                            console.log('=====>', info);
                            init(currentIpIndex,info.data,true);
                        }
                    }
                }

            };
            ws1.onerror = function (err) {
                totalCount++;
                if(totalCount >= 255 && !startStopServer){
                    totalCount = 0;
                    currentIpIndex = 255;
                    getIpING = false;
                    socket.getIp1();
                }
            }

            if (exactDomainIp) {
                break;
            }
        }
    }

}

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

const  getClose = ()=>{
    //如果有currentIp就没有必要再次循环
    ws = null;
    beginConnectSocket();
}



const init = (ip,storeid,from = false)=>{
    let theIp = exactDomainIp || `${domainIp}${ip}`;
    let wsUrl = `ws://${theIp}:${domainPort}/notify?from=plant&storeId=${storeid}`;
    // if("WebSocket" in window && !ws && storeid &&
    //         (exactDomainIp || (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(exactDomainIp || (domainIp + ip));
    //         // if(stopTimer){
    //         //     //重连成功后，终止倒计时
    //         //     clearTimeout(stopTimer);
    //         //     stopTimer = null;
    //         //     startStopServer = false;
    //         //     myLogger.info("连接成功，停止stopTimer倒计时");
    //         // }
    //         // emit(CONFIG.socketType.GETSTOREINFO,{ip:(exactDomainIp || (domainIp + ip)),storeId:storeid})
    //     };
    //
    //     ws.onmessage = function (evt)
    //     {
    //         // if(evt.data === "ping"){
    //         //     let o = {
    //         //         type : 'PONG'
    //         //     };
    //         //     ws.send(JSON.stringify(o));
    //         // }else{
    //         //     let 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;