export default class Polling {
    // сигнатура по примеру setInterval(fn, period)
    constructor(pollFunction, period = 0) {
        this.counter = 0;
        this.period = period;
        this.running = false;

        this._poll = mode => {
            let output;

            if (mode !== 'delayed') {
                output = pollFunction.call(this, this.counter);

                if (this.counter !== Number.MAX_SAFE_INTEGER) {
                    this.counter++;
                }

                this.polledAt = Date.now();
            }

            if (this.running) {
                this._next = setTimeout(() => this._poll(), this.getDelay());
            }

            return output;
        };
    }

    start(mode) {
        clearTimeout(this._next);

        this.counter = 0;
        this.running = true;

        return Promise.resolve(this._poll(mode));
    }

    stop() {
        clearTimeout(this._next);

        this.running = false;
    }

    getDelay() {
        return typeof this.period === 'function' ?
            // нелинейный поллинг
            this.period(this.counter) :
            // линейный поллинг
            this.period;
    }
}
