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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9uaXRvci1lbmdpbmUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi9kYXRhL3NyYy9saWIvbW9uaXRvci9tb25pdG9yLWVuZ2luZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFBQSxPQUFPLEVBQ0wsZUFBZSxFQUNmLEtBQUssRUFDTCxLQUFLLEVBRUwsS0FBSyxHQUVOLE1BQU0sTUFBTSxDQUFDO0FBQ2QsT0FBTyxFQUFFLEdBQUcsRUFBRSxPQUFPLEVBQUUsS0FBSyxFQUFFLFNBQVMsRUFBRSxNQUFNLGdCQUFnQixDQUFDO0FBRWhFLE9BQU8sRUFDTCxhQUFhLEdBRWQsTUFBTSxpQ0FBaUMsQ0FBQztBQUd6QyxNQUFNLEdBQUcsR0FBRyxrQkFBa0IsQ0FBQztBQTJCL0IsTUFBTSxPQUFPLG9CQUFvQjtJQUsvQixZQUNrQixjQUEwQyx3QkFBd0I7UUFBbEUsZ0JBQVcsR0FBWCxXQUFXLENBQXVEO1FBTDVFLFlBQU8sR0FBRyxJQUFJLGVBQWUsQ0FDbkMsSUFBSSxDQUFDLFdBQVcsQ0FDakIsQ0FBQztJQUlDLENBQUM7SU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