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());
    });
};
import { BehaviorSubject, empty, never, timer } from 'rxjs';
import { map, flatMap, share, switchMap } from 'rxjs/operators';
import { MonitorEngine } from '../api/monitor-engine.interface';
const TAG = 'TapMonitorEngine';
export class MonitoringController {
    constructor(initalState = INITAL_MONITORING_CONFIG) {
        this.initalState = initalState;
        this.subject = new BehaviorSubject(this.initalState);
    }
    get state() {
        return this.subject.value.state;
    }
    start(options) {
        this.subject.next(Object.assign({
            state: MonitorEngine.State.START
        }, options));
        return this;
    }
    stop() {
        this.subject.next({
            state: MonitorEngine.State.STOP
        });
        return this;
    }
    pause() {
        this.subject.next({
            state: MonitorEngine.State.PAUSE
        });
        return this;
    }
    setPeriod(period) {
        this.subject.next({
            period
        });
    }
    asSubject() {
        return this.subject;
    }
}
export function createDataStreamMonitor(stream, ticker, eventSubject) {
    return ticker
        .pipe(flatMap((tickerState) => __awaiter(this, void 0, void 0, function* () {
        // debug(TAG, `Running call at time ${time}`);
        return stream.readRaw()
            .then(value => {
            // TODO event ?
            return value;
        })
            .catch((error) => {
            eventSubject.next({
                type: 'error',
                error,
                stream,
                timerState: tickerState
            });
        });
    })), 
    // filter<DataType | undefined, DataType>((value): value is DataType => {
    //     return value !== undefined;
    // }),
    share());
}
const INITAL_MONITORING_CONFIG = {
    dueTime: 0,
    period: 1000,
    refresh: false,
    state: MonitorEngine.State.STOP
};
export function createMonitoringTicker(
// call: (time: number) => Promise<DataType>,
controller) {
    const controllerSubject = controller instanceof MonitoringController ? controller.asSubject() : controller;
    let lastState = Object.assign(Object.assign({}, INITAL_MONITORING_CONFIG), controllerSubject.value);
    return controllerSubject
        .pipe(switchMap((partialState) => {
        const newState = Object.assign(Object.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((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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9uaXRvci1lbmdpbmUuanMiLCJzb3VyY2VSb290Ijoibmc6Ly9AaW90aXplL3RhcC9kYXRhLyIsInNvdXJjZXMiOlsibGliL21vbml0b3IvbW9uaXRvci1lbmdpbmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUEsT0FBTyxFQUFFLGVBQWUsRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFjLEtBQUssRUFBVyxNQUFNLE1BQU0sQ0FBQztBQUNqRixPQUFPLEVBQUUsR0FBRyxFQUFFLE9BQU8sRUFBRSxLQUFLLEVBQUUsU0FBUyxFQUFFLE1BQU0sZ0JBQWdCLENBQUM7QUFFaEUsT0FBTyxFQUFFLGFBQWEsRUFBMEIsTUFBTSxpQ0FBaUMsQ0FBQztBQUd4RixNQUFNLEdBQUcsR0FBRyxrQkFBa0IsQ0FBQztBQTBCL0IsTUFBTSxPQUFPLG9CQUFvQjtJQUs3QixZQUE0QixjQUEwQyx3QkFBd0I7UUFBbEUsZ0JBQVcsR0FBWCxXQUFXLENBQXVEO1FBRnRGLFlBQU8sR0FBRyxJQUFJLGVBQWUsQ0FBc0MsSUFBSSxDQUFDLFdBQVcsQ0FBQyxDQUFDO0lBRUssQ0FBQztJQUVuRyxJQUFJLEtBQUs7U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