self.importScripts('wasmcommon.js');
/**
 * wesoket的实体类
 * @constructor
 */

function Downloaderenvent() {
    this.logger = new Logger('Downloader');
    this.Socket = null;
    this.enventurl = "";
    this.enventtype = "";
    this.enventmsg = "";
}


Downloaderenvent.prototype.reportWasmdataenvent = function(code, data) {
    var objData = {
        t: kGetwasmRspenvent,
        i: {
            code: code,
            data: data,
        }
    };
    self.postMessage(objData)
};

Downloaderenvent.prototype.requestenventWebsocket = function(url, msg, type, cb) {
    if (!this.Socket) {
        this.Socket = new WebSocket(url);
        if (type != "") {
            this.Socket.binaryType = type;
        }
        var self = this;
        self.Socket.onopen = function() {
            if (self.Socket.readyState == 1) {
                self.Socket.send(msg);
            }
        };
        self.Socket.onerror = function(e) {
            console.log("onerror:" + e.currentTarget.readyState);
            this.Socket.close();
        };
        self.Socket.onclose = function(e) {
            console.log("connect closed:" + e.code + "connect reason" + e.reason + "connect wasClean" + e.wasClean);
            this.Socket.updateenvent()
        };
        self.Socket.onmessage = cb.onenventmessage;
    } else {
        this.Socket.send(msg);
        // this.Socket=null;
    }

};






Downloaderenvent.prototype.updateenvent = function() {
    this.Socket = null;
    var that = this;
    setTimeout(function() {
        that.requestenventWebsocket(that.enventurl, JSON.stringify(that.enventmsg), that.enventtype, {
            onenventmessage: function(evt) {
                var data = evt.data;
                that.reportWasmdataenvent(200, data)
            },
        })
    }, 2000);

};



Downloaderenvent.prototype.getenventByWebsocket = function(url, msg, type) {
    var data = null;
    var self = this;
    self.enventurl = url;
    self.enventmsg = msg;
    self.enventtype = type;
    this.requestenventWebsocket(url, JSON.stringify(msg), type, {
        onenventmessage: function(evt) {
            data = evt.data;
            self.reportWasmdataenvent(200, data)
        },
    })
};




self.downloaderenvent = new Downloaderenvent();

self.onmessage = function(evt) {
    if (!self.downloaderenvent) {
        console.log('[ER] downloaderenvent not initialized!');
        return
    }
    var objData = evt.data;
    switch (objData.t) {
        case kGetwasmReqenvent:
            self.downloaderenvent.getenventByWebsocket(objData.url, objData.msg, objData.type);
            break;
        default:
            self.downloaderenvent.logger.logError('Unsupport messsage' + objData.t)
    }
};