"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const events = require("events");
const activelogger_1 = require("@activeledger/activelogger");
class ActiveChanges extends events.EventEmitter {
    constructor(name, db, limit) {
        super();
        this.name = name;
        this.db = db;
        this.limit = limit;
        this.restarting = false;
    }
    start(since = "now") {
        if (!this.dbChanges) {
            activelogger_1.ActiveLogger.info("Starting Change Feed - " + this.name);
            if (this.lastSequence) {
                since = this.lastSequence;
            }
            this.dbChanges = this.db.changes({
                since: since,
                live: true,
                include_docs: true,
                timeout: false,
                limit: this.limit || 25
            });
            this.dbChanges.on("change", (change) => {
                this.lastSequence = change.seq;
                this.emit("change", change);
            });
            this.dbChanges.on("error", (e) => {
                if (!this.restarting) {
                    this.restarting = true;
                    this.pause();
                    this.resume(true);
                }
            });
        }
    }
    pause() {
        if (this.dbChanges) {
            this.dbChanges.cancel();
            this.dbChanges = null;
        }
    }
    resume(force = false) {
        if (force || !this.restarting) {
            setTimeout(() => {
                activelogger_1.ActiveLogger.info("Attempting Restarting Change Feed - " + this.name);
                this.db
                    .info()
                    .then((info) => {
                    if (this.lastSequence && this.lastSequence > info.update_seq) {
                        this.lastSequence = info.update_seq;
                    }
                    this.restarting = false;
                    this.start();
                })
                    .catch(() => {
                    setTimeout(() => {
                        this.resume(true);
                    }, 1500);
                });
            }, 1500);
        }
    }
    stop() {
        this.lastSequence = undefined;
        this.dbChanges.cancel();
        this.dbChanges = null;
    }
}
exports.ActiveChanges = ActiveChanges;
//# sourceMappingURL=changes.js.map