"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Event = exports.EventService = void 0;
const events_1 = require("events");
const Loggify_1 = require("../decorators/Loggify");
const logger_1 = __importDefault(require("../logger"));
const events_2 = require("../models/events");
const config_1 = require("./config");
const storage_1 = require("./storage");
let EventService = class EventService {
    constructor({ storageService = storage_1.Storage, eventModel = events_2.EventStorage, configService = config_1.Config } = {}) {
        this.txEvent = new events_1.EventEmitter();
        this.blockEvent = new events_1.EventEmitter();
        this.addressCoinEvent = new events_1.EventEmitter();
        this.events = new events_1.EventEmitter();
        this.stopped = false;
        this.storageService = storageService;
        this.configService = configService;
        this.eventModel = eventModel;
        this.signalTx = this.signalTx.bind(this);
        this.signalBlock = this.signalBlock.bind(this);
        this.signalAddressCoin = this.signalAddressCoin.bind(this);
    }
    start() {
        if (this.configService.isDisabled('event')) {
            logger_1.default.info('Disabled Event Service');
            return;
        }
        logger_1.default.info('Starting Event Service');
        this.stopped = false;
        this.events.emit('start');
        if (this.storageService.connected) {
            this.wireup();
        }
        else {
            this.storageService.connection.on('CONNECTED', () => {
                this.wireup();
            });
        }
    }
    async stop() {
        logger_1.default.info('Stopping Event Service');
        this.stopped = true;
        this.events.emit('stop');
        this.events.removeAllListeners();
        this.txEvent.removeAllListeners();
        this.blockEvent.removeAllListeners();
        this.addressCoinEvent.removeAllListeners();
    }
    async wireup() {
        let lastBlockUpdate = new Date();
        let lastTxUpdate = new Date();
        let lastAddressTxUpdate = new Date();
        const retryTxCursor = async () => {
            try {
                const txCursor = this.eventModel.getTxTail(lastTxUpdate);
                while (!this.stopped && (await txCursor.hasNext())) {
                    const txEvent = await txCursor.next();
                    if (txEvent) {
                        const tx = txEvent.payload;
                        this.txEvent.emit('tx', tx);
                        lastTxUpdate = new Date();
                    }
                }
            }
            catch (err) {
                logger_1.default.error('Error in retryTxCursor:', err);
            }
            finally {
                if (!this.stopped) {
                    setTimeout(retryTxCursor, 100);
                }
            }
        };
        retryTxCursor();
        const retryBlockCursor = async () => {
            try {
                const blockCursor = this.eventModel.getBlockTail(lastBlockUpdate);
                while (!this.stopped && (await blockCursor.hasNext())) {
                    const blockEvent = await blockCursor.next();
                    if (blockEvent) {
                        const block = blockEvent.payload;
                        this.blockEvent.emit('block', block);
                        lastBlockUpdate = new Date();
                    }
                }
            }
            catch (err) {
                logger_1.default.error('Error in retryBlockCursor:', err);
            }
            finally {
                if (!this.stopped) {
                    setTimeout(retryBlockCursor, 100);
                }
            }
        };
        retryBlockCursor();
        const retryAddressTxCursor = async () => {
            try {
                const addressTxCursor = this.eventModel.getCoinTail(lastAddressTxUpdate);
                while (!this.stopped && (await addressTxCursor.hasNext())) {
                    const addressTx = await addressTxCursor.next();
                    if (addressTx) {
                        const addressCoin = addressTx.payload;
                        this.addressCoinEvent.emit('coin', addressCoin);
                        lastAddressTxUpdate = new Date();
                    }
                }
            }
            catch (err) {
                logger_1.default.error('Error in retryAddressTxCursor:', err);
            }
            finally {
                if (!this.stopped) {
                    setTimeout(retryAddressTxCursor, 100);
                }
            }
        };
        retryAddressTxCursor();
    }
    async signalBlock(block) {
        await this.eventModel.signalBlock(block);
    }
    async signalTx(tx) {
        await this.eventModel.signalTx(tx);
    }
    async signalAddressCoin(payload) {
        await this.eventModel.signalAddressCoin(payload);
    }
};
exports.EventService = EventService;
exports.EventService = EventService = __decorate([
    Loggify_1.LoggifyClass
], EventService);
exports.Event = new EventService();
//# sourceMappingURL=event.js.map