"use strict";
class pool {
constructor(opt = 'http://localhost:3001', cb) {
this.cursor = 0;
this.serverURI = null;
this.update = this.firstUpdate;
this.merge = this.defalutmerge;
if (typeof opt === 'string') {
this.serverURI = opt;
this.fetchDataFromServer(cb);
}
else
this.refreshData(opt, cb);
}
;
refreshData(data, cb) {
this.data = new Map();
data.forEach(d => { this.data.set(d.k, d.v); });
if (cb)
cb();
}
firstUpdate(data) {
this.oridata = new Map(this.data);
this.update = this._update;
this._update(data);
}
_update(data) {
data.forEach(d => this.data.set(d.k, d.v));
if (this.onDataUpdate)
this.onDataUpdate(data);
}
;
openSocket() {
this.merge = this.socketMerge;
this.socket = io.connect(this.serverURI+"/test"), {
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax': 5000,
'reconnectionAttempts': 5
};
this.socket.on("update", data => {
this.update(data);
this.mergeLocal;
if (this.onSocketDataUpdate)
this.onSocketDataUpdate(data);
});
}
;
closeSocket() {
this.socket.closeSocket();
this.merge = this.defalutmerge;
}
;
socketMerge() {
var diff = this.mergeLocal();
this.socket.emit("update", diff);
}
;
fetctNext(count = 10) {
let tmp = [];
let upBound = this.cursor + count;
let lwBound = this.cursor;
let i = 0;
this.data.forEach((v, k) => {
if ((i++ < upBound) && (i > lwBound))
tmp.push({ k: k, v: v });
});
this.cursor = upBound;
return tmp;
}
mergeLocal(checkDiff = true) {
let diff = [];
if (checkDiff)
this.data.forEach((v, k) => {
if (v !== this.oridata.get(k))
diff.push({ k: k, v: v });
});
this.oridata = new Map(this.data);
return diff;
}
;
defalutmerge() {
var diff = this.mergeLocal();
d3.json(this.serverURI + "/update", {
method: "POST",
body: JSON.stringify(diff),
headers: { "Content-type": "application/json; charset=UTF-8" }
}).then(console.log);
}
;
fetchDataFromServer(cb) {
d3.json(this.serverURI + "/data").then(json => this.refreshData(json, cb));
}
;
dump() {
let tmp = [];
this.data.forEach((v, k) => { tmp.push({ k: k, v: v }); });
return tmp;
}
;
recreate() {
var tmp = new Map();
this.dump().forEach(d => { tmp.set(d.k, d.v); });
}
;
delete(data) {
let rr = [];
data.forEach(d => {
if ((this.data.has(d.k)) && (this.data.get(d.k) === d.v)) {
this.data.delete(d.k);
rr.push(true);
}
else
rr.push(false);
});
return rr;
}
}