var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { BehaviorSubject, empty, never, timer } from 'rxjs';
import { map, flatMap, share, switchMap } from 'rxjs/operators';
import { MonitorEngine } from '../api/monitor-engine.interface';
var TAG = 'TapMonitorEngine';
var MonitoringController = /** @class */ (function () {
    function MonitoringController(initalState) {
        if (initalState === void 0) { initalState = INITAL_MONITORING_CONFIG; }
        this.initalState = initalState;
        this.subject = new BehaviorSubject(this.initalState);
    }
    Object.defineProperty(MonitoringController.prototype, "state", {
        get: function () {
            return this.subject.value.state;
        },
        enumerable: true,
        configurable: true
    });
    MonitoringController.prototype.start = function (options) {
        this.subject.next(__assign({
            state: MonitorEngine.State.START
        }, options));
        return this;
    };
    MonitoringController.prototype.stop = function () {
        this.subject.next({
            state: MonitorEngine.State.STOP
        });
        return this;
    };
    MonitoringController.prototype.pause = function () {
        this.subject.next({
            state: MonitorEngine.State.PAUSE
        });
        return this;
    };
    MonitoringController.prototype.setPeriod = function (period) {
        this.subject.next({
            period: period
        });
    };
    MonitoringController.prototype.asSubject = function () {
        return this.subject;
    };
    return MonitoringController;
}());
export { MonitoringController };
export function createDataStreamMonitor(stream, ticker, eventSubject) {
    var _this = this;
    return ticker
        .pipe(flatMap(function (tickerState) { return __awaiter(_this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            // debug(TAG, `Running call at time ${time}`);
            return [2 /*return*/, stream.readRaw()
                    .then(function (value) {
                    // TODO event ?
                    return value;
                })
                    .catch(function (error) {
                    eventSubject.next({
                        type: 'error',
                        error: error,
                        stream: stream,
                        timerState: tickerState
                    });
                })];
        });
    }); }), 
    // filter<DataType | undefined, DataType>((value): value is DataType => {
    //     return value !== undefined;
    // }),
    share());
}
var INITAL_MONITORING_CONFIG = {
    dueTime: 0,
    period: 1000,
    refresh: false,
    state: MonitorEngine.State.STOP
};
export function createMonitoringTicker(
// call: (time: number) => Promise<DataType>,
controller) {
    var controllerSubject = controller instanceof MonitoringController ? controller.asSubject() : controller;
    var lastState = __assign(__assign({}, INITAL_MONITORING_CONFIG), controllerSubject.value);
    return controllerSubject
        .pipe(switchMap(function (partialState) {
        var newState = __assign(__assign({}, lastState), partialState);
        lastState = newState;
        // console.log(TAG, 'Apply new monitoring state: ', newState);
        switch (newState.state) {
            case MonitorEngine.State.STOP:
                return empty();
            case MonitorEngine.State.START:
                return timer(newState.dueTime, newState.period)
                    .pipe(map(function (time) { return ({
                    time: time,
                    state: newState
                }); }));
            case MonitorEngine.State.PAUSE:
                return never();
            default:
                throw new Error("InternalErorr: Not implemented monitoring state: " + newState.state);
        }
    }));
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9uaXRvci1lbmdpbmUuanMiLCJzb3VyY2VSb290Ijoibmc6Ly9AaW90aXplL3RhcC9kYXRhLyIsInNvdXJjZXMiOlsibGliL21vbml0b3IvbW9uaXRvci1lbmdpbmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBQSxPQUFPLEVBQUUsZUFBZSxFQUFFLEtBQUssRUFBRSxLQUFLLEVBQWMsS0FBSyxFQUFXLE1BQU0sTUFBTSxDQUFDO0FBQ2pGLE9BQU8sRUFBRSxHQUFHLEVBQUUsT0FBTyxFQUFFLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSxnQkFBZ0IsQ0FBQztBQUVoRSxPQUFPLEVBQUUsYUFBYSxFQUEwQixNQUFNLGlDQUFpQyxDQUFDO0FBR3hGLElBQU0sR0FBRyxHQUFHLGtCQUFrQixDQUFDO0FBMEIvQjtJQUtJLDhCQUE0QixXQUFrRTtRQ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