"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.lostAfterSelection = exports.nodesYetToStartSyncing = void 0;
exports.addSyncStarted = addSyncStarted;
exports.drainSyncStarted = drainSyncStarted;
exports.drainLostAfterSelectionNodes = drainLostAfterSelectionNodes;
const logger_1 = require("../../../logger");
const NodeList = __importStar(require("../../NodeList"));
const CycleChain = __importStar(require("../../CycleChain"));
const Context_1 = require("../../Context");
// import * as utils from '../../../utils'
// import { getRandomAvailableArchiver, getActiveNodesFromArchiver } from '../../Utils'
//import * as http from '../../../http'
const CycleCreator_1 = require("../../CycleCreator");
// import { ok, Result } from 'neverthrow'
exports.nodesYetToStartSyncing = new Map();
exports.lostAfterSelection = [];
let newSyncStarted = new Map();
/*
Currently not used

export async function submitSyncStarted(payload: SyncStarted): Promise<Result<void, Error>> {
  const archiver = getRandomAvailableArchiver()
  try {
    const activeNodesResult = await getActiveNodesFromArchiver(archiver)
    if (activeNodesResult.isErr()) {
      throw Error(`couldn't get active nodes: ${activeNodesResult.error}`)
    }
    const activeNodes = activeNodesResult.value
    const node = utils.getRandom(activeNodes.nodeList, 1)[0]
    await http.post(`${node.ip}:${node.port}/sync-started`, payload)
    return ok(void 0)
  } catch (e) {
    throw Error(`submitSyncStarted: Error posting syncStarted request: ${e}`)
  }
}
*/
function addSyncStarted(syncStarted) {
    // lookup node by id in payload and use pubkey and compare to sig.owner
    const publicKeysMatch = NodeList.byIdOrder.find((node) => node.id === syncStarted.nodeId)?.publicKey === syncStarted.sign.owner;
    if (!publicKeysMatch) {
        return {
            success: false,
            reason: 'public key in syncStarted request does not match public key of node',
            fatal: false,
        };
    }
    // cycle number check
    const cycleNumber = CycleChain.getNewest().counter;
    if (cycleNumber !== syncStarted.cycleNumber) {
        return {
            success: false,
            reason: 'cycle number in syncStarted request does not match current cycle number',
            fatal: false,
        };
    }
    // return false if already in map
    if (newSyncStarted.has(syncStarted.nodeId) === true) {
        return {
            success: false,
            reason: 'node has already submitted syncStarted request',
            fatal: false,
        };
    }
    if (!Context_1.crypto.verify(syncStarted, syncStarted.sign.owner)) {
        return {
            success: false,
            reason: 'verification of syncStarted request failed',
            fatal: false,
        };
    }
    newSyncStarted.set(syncStarted.nodeId, syncStarted);
    return {
        success: true,
        reason: 'syncStarted passed all checks and verification',
        fatal: false,
    };
}
/**
 * Returns the list of nodeIds of nodes that started syncing empties the map.
 */
function drainSyncStarted() {
    if (CycleCreator_1.currentQuarter === 3) {
        if (logger_1.logFlags.verbose)
            console.log('draining new syncStarted info:', newSyncStarted);
        const tmp = newSyncStarted;
        newSyncStarted = new Map();
        return [...tmp.entries()].sort((a, b) => a[0].localeCompare(b[0])).map((entry) => entry[1]);
    }
    else {
        return [];
    }
}
function drainLostAfterSelectionNodes() {
    if (CycleCreator_1.currentQuarter === 3) {
        if (logger_1.logFlags.verbose)
            console.log('draining lost after selection nodes:', exports.lostAfterSelection);
        const tmp = exports.lostAfterSelection;
        exports.lostAfterSelection = [];
        return tmp.sort();
    }
    else {
        return [];
    }
}
//# sourceMappingURL=syncStarted.js.map