"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateStorage = exports.StateModel = void 0;
const os_1 = __importDefault(require("os"));
const base_1 = require("./base");
class StateModel extends base_1.BaseModel {
    constructor(storage) {
        super('state', storage);
        this.allowedPaging = [];
    }
    onConnect() { }
    async getSingletonState() {
        return this.collection.findOneAndUpdate({}, { $setOnInsert: { created: new Date() } }, { upsert: true, returnOriginal: false });
    }
    async getSyncingNode(params) {
        const { chain, network } = params;
        const state = await this.getSingletonState();
        return state.value[`syncingNode:${chain}:${network}`];
    }
    async selfNominateSyncingNode(params) {
        const { chain, network, lastHeartBeat } = params;
        const singleState = await this.getSingletonState();
        return this.collection.findOneAndUpdate({
            _id: singleState.value._id,
            $or: [
                { [`syncingNode:${chain}:${network}`]: { $exists: false } },
                { [`syncingNode:${chain}:${network}`]: lastHeartBeat }
            ]
        }, { $set: { [`syncingNode:${chain}:${network}`]: `${os_1.default.hostname}:${process.pid}:${Date.now()}` } });
    }
    async selfResignSyncingNode(params) {
        const { chain, network, lastHeartBeat } = params;
        const singleState = await this.getSingletonState();
        return this.collection.findOneAndUpdate({ _id: singleState.value._id, [`syncingNode:${chain}:${network}`]: lastHeartBeat }, { $unset: { [`syncingNode:${chain}:${network}`]: true } });
    }
    setVerifiedBlockHeight(params) {
        const { chain, network, height } = params;
        return this.collection.updateOne({}, {
            $addToSet: { initialSyncComplete: `${chain}:${network}` },
            $set: { [`verifiedBlockHeight.${chain}.${network}`]: height }
        }, { upsert: true });
    }
    setLastAddressSubscriptionUpdate(params) {
        const { chain, network, timestamp } = params;
        return this.collection.updateOne({}, {
            $addToSet: { initialSyncComplete: `${chain}:${network}` },
            $set: { [`lastAddressSubscriptionUpdate.${chain}.${network}`]: timestamp }
        }, { upsert: true });
    }
}
exports.StateModel = StateModel;
exports.StateStorage = new StateModel();
//# sourceMappingURL=state.js.map