"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getClusterPools = getClusterPools;
// @ts-ignore
const javascript_wrapper_1 = __importDefault(require("@ytsaurus/javascript-wrapper"));
const yt_api_1 = require("../../shared/constants/yt-api");
const utils_1 = require("../utils");
const requestsSetup_1 = require("../components/requestsSetup");
const yt = (0, javascript_wrapper_1.default)();
async function getClusterPools(req, res) {
    try {
        req.ctx.log('Test', req.params);
        const { ytAuthCluster } = req.params;
        const { poolTree } = req.query;
        let cfg;
        try {
            cfg = (0, requestsSetup_1.getUserYTApiSetup)(ytAuthCluster, req);
        }
        catch (e) {
            (0, utils_1.sendAndLogError)(req.ctx, res, 400, e);
            return;
        }
        const { setup } = cfg;
        const { names, tree } = await loadPoolTree(setup, poolTree);
        res.send({ tree, names });
    }
    catch (e) {
        (0, utils_1.sendAndLogError)(req.ctx, res, null, e);
    }
}
const SCHEDULER_POOL_TREES = '//sys/scheduler/config/pool_trees_root';
async function loadPoolTree(setup, poolTree) {
    const poolTreesRoot = await getPoolTreeRootPath(setup);
    const tree = poolTree ? poolTree : await loadDefaultPoolTree(setup, poolTreesRoot);
    const data = await yt.v3.get({
        setup,
        parameters: { path: `${poolTreesRoot}/${tree}`, ...yt_api_1.USE_MAX_SIZE },
    });
    const names = [];
    const stack = [data];
    while (stack.length) {
        const item = stack.pop();
        Object.keys(item ?? {}).forEach((k) => {
            names.push(k);
            if (item) {
                stack.push(item[k]);
            }
        });
    }
    return { names, tree };
}
function getPoolTreeRootPath(setup) {
    return yt.v3.get({ setup, parameters: { path: SCHEDULER_POOL_TREES } }).then((path) => {
        return path;
    }, (err) => {
        return err.code === yt.codes.NODE_DOES_NOT_EXIST
            ? '//sys/pool_trees'
            : Promise.reject(err);
    });
}
async function loadDefaultPoolTree(setup, poolTreesRoot) {
    const path = `${poolTreesRoot}/@default_tree`;
    return yt.v3
        .get({ setup, parameters: { path } })
        .then((defaultTree) => {
        return defaultTree || 'physical';
    })
        .catch((error) => {
        if (error && error.code === yt.codes.NODE_DOES_NOT_EXIST) {
            return 'physical';
        }
        throw error;
    });
}
