import * as msgpack from 'msgpack-lite';

class DeviceHttpDataSource {

    constructor(dataUrl, onNewData, pollInterval=800, startIndex = 0) {
        this.dataUrl = dataUrl;
        this.onNewData = onNewData;
        this.pollInterval = pollInterval;
        this.startIndex = startIndex;
        this.timer = null;

        // msgpack setup
        this.msgpackCodec = msgpack.createCodec();
        this.msgpackCodec.addExtUnpacker(205, function (byteArr) {
            const buffer = byteArr.buffer.slice(byteArr.byteOffset, byteArr.byteLength + byteArr.byteOffset);
            const result = new Int16Array(buffer);
            return result;
        });

        this.fetchDataHttp = this.fetchDataHttp.bind(this);
    }

    getUrl(url) {
        return new Promise((accept, reject) => {
            var req = new XMLHttpRequest();
            req.open("GET", url, true);
            req.responseType = "arraybuffer";

            req.onload = function (event) {
                var resp = req.response;
                if (resp) {
                    accept(resp);
                }
            };
            req.addEventListener("error", evt => reject(evt));
            req.addEventListener("abort", evt => reject(evt));

            req.send(null);
        });
    }

    async fetchDataHttp() {
        try {
            const url = this.dataUrl + "?startIdx=" + this.startIndex;
            const arrayBuffer = await this.getUrl(url);
            const decoded = msgpack.decode(new Uint8Array(arrayBuffer), { codec: this.msgpackCodec });
            this.startIndex += decoded["values"].length;
            this.onNewData(decoded);
        } catch (err) {
            console.log(err);
        }
    }

    start() {
        if (this.timer === null) {
            console.log("Start monitoring");
            this.timer = setInterval(this.fetchDataHttp, this.pollInterval);
            return true;
        } else {
            return false;
        }
    }

    stop() {
        if (this.timer !== null) {
            console.log("stop monitoring");
            clearInterval(this.timer);
            this.timer = null;
            return true;
        } else {
            return false;
        }
    }
};

export default DeviceHttpDataSource;
