"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getColumnPreset = getColumnPreset;
exports.saveColumnPreset = saveColumnPreset;
const some_1 = __importDefault(require("lodash/some"));
const object_hash_1 = __importDefault(require("object-hash"));
// @ts-ignore-next-line
const javascript_wrapper_1 = __importDefault(require("@ytsaurus/javascript-wrapper"));
const requestsSetup_1 = require("./requestsSetup");
const yt = (0, javascript_wrapper_1.default)();
const SHA1_REGEXP = /^[0-9a-f]{40}$/;
async function getColumnPreset({ dynamicTablePath, cluster }, hash, ytAuthCluster) {
    if (!SHA1_REGEXP.test(hash)) {
        throw new Error('The hash parameter should be defined as a valid sha1-hash string');
    }
    const { setup: setupConfig } = (0, requestsSetup_1.getRobotYTApiSetup)(cluster || ytAuthCluster);
    const query = `* FROM [${dynamicTablePath}] WHERE hash="${hash}" LIMIT 1`;
    const result = await yt.v3.selectRows({
        setup: setupConfig,
        parameters: {
            query,
            output_format: {
                $value: 'json',
                $attributes: {
                    field_weight_limit: 100000,
                    encode_utf8: 'false',
                },
            },
        },
    });
    if (!result) {
        return undefined;
    }
    let columns = [];
    try {
        columns = JSON.parse(JSON.parse(result).columns_json);
    }
    catch (e) {
        throw new Error(`Failed to parse ${hash}-preset`);
    }
    if (!Array.isArray(columns) || (0, some_1.default)(columns, (i) => 'string' !== typeof i)) {
        throw new Error(`${hash}-preset is not an array of strings`);
    }
    return columns;
}
async function saveColumnPreset({ dynamicTablePath, cluster }, columns, ytAuthCluster) {
    if (!Array.isArray(columns) || (0, some_1.default)(columns, (i) => 'string' !== typeof i)) {
        throw new Error('Request body should contain JSON-array of strings');
    }
    const { setup: setupConfig } = (0, requestsSetup_1.getRobotYTApiSetup)(cluster || ytAuthCluster);
    const hash = object_hash_1.default.sha1(columns);
    await yt.v3.insertRows({
        setup: setupConfig,
        parameters: {
            path: dynamicTablePath,
            input_format: {
                $value: 'json',
                $attributes: {
                    encode_utf8: 'false',
                },
            },
        },
        data: [{ hash, columns_json: JSON.stringify(columns) }],
    });
    return hash;
}
