"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.drainNewStandbyRefreshRequests = exports.addStandbyRefresh = exports.submitStandbyRefresh = void 0;
const Utils_1 = require("../../Utils");
const utils = __importStar(require("../../../utils"));
const http = __importStar(require("../../../http"));
const neverthrow_1 = require("neverthrow");
const logger_1 = require("../../../logger");
const index_1 = require("./index");
const CycleChain = __importStar(require("../../CycleChain"));
const Context_1 = require("../../Context");
const Context_2 = require("../../Context");
let newStandbyRefreshRequests = new Map();
async function submitStandbyRefresh(publicKey) {
    const archiver = (0, Utils_1.getRandomAvailableArchiver)();
    try {
        const activeNodesResult = await (0, Utils_1.getActiveNodesFromArchiver)(archiver);
        if (activeNodesResult.isErr()) {
            throw Error(`couldn't get active nodes: ${activeNodesResult.error}`);
        }
        const activeNodes = activeNodesResult.value;
        const maxRetries = 3;
        let attempts = 0;
        const queriedNodesPKs = [];
        while (attempts < maxRetries) {
            try {
                let node;
                let pickNodeAttempts = 5;
                do {
                    if (pickNodeAttempts === 0)
                        throw Error('submitStandbyRefresh: No active nodes to query');
                    node = utils.getRandom(activeNodes.nodeList, 1)[0];
                    pickNodeAttempts--;
                } while (queriedNodesPKs.includes(node.publicKey));
                queriedNodesPKs.push(node.publicKey);
                await http.post(`${node.ip}:${node.port}/standby-refresh`, { publicKey });
                return (0, neverthrow_1.ok)(void 0);
            }
            catch (e) {
                console.error(`Attempt ${attempts + 1} failed: ${e}`);
                attempts++;
                utils.sleep(Context_2.config.p2p.resumbitStandbyRefreshWaitDuration); // Sleep for 1 second before retrying
            }
        }
        // If the code reaches this point, all retries have failed
        throw Error('All attempts to post standbyRefresh request failed');
    }
    catch (e) {
        // This catch block will handle errors from getActiveNodesFromArchiver and if all retries fail
        throw Error(`submitStandbyRefresh: Error posting standbyRefresh request: ${e}`);
    }
}
exports.submitStandbyRefresh = submitStandbyRefresh;
function addStandbyRefresh(standbyRefreshRequest) {
    // validate keepInStandbyRequest
    if (!(0, index_1.isOnStandbyList)(standbyRefreshRequest.publicKey)) {
        return {
            success: false,
            reason: 'Node not found in standby list',
            fatal: false,
        };
    }
    // cycle number check
    const cycleNumber = CycleChain.getNewest().counter;
    if (cycleNumber !== standbyRefreshRequest.cycleNumber) {
        return {
            success: false,
            reason: 'cycle number in StandbyRefreshRequest request does not match current cycle number',
            fatal: false,
        };
    }
    //add it to TXs
    if (newStandbyRefreshRequests.has(standbyRefreshRequest.publicKey) === true) {
        return {
            success: false,
            reason: 'Node already in standby refresh list',
            fatal: false,
        };
    }
    if (!Context_1.crypto.verify(standbyRefreshRequest, standbyRefreshRequest.sign.owner)) {
        return {
            success: false,
            reason: 'verification of syncStarted request failed',
            fatal: false,
        };
    }
    newStandbyRefreshRequests.set(standbyRefreshRequest.publicKey, standbyRefreshRequest);
    return {
        success: true,
        reason: 'standbyRefreshRequest passed all checks and verification',
        fatal: false,
    };
}
exports.addStandbyRefresh = addStandbyRefresh;
/**
 * Returns the list of new StandbyRefreshRequest requests and empties the list.
 */
function drainNewStandbyRefreshRequests() {
    if (logger_1.logFlags.verbose)
        console.log('draining new StandbyRefreshRequest info:', newStandbyRefreshRequests);
    const tmp = Array.from(newStandbyRefreshRequests.values());
    newStandbyRefreshRequests = new Map();
    return tmp;
}
exports.drainNewStandbyRefreshRequests = drainNewStandbyRefreshRequests;
//# sourceMappingURL=standbyRefresh.js.map