"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tableColumnPresetGet = tableColumnPresetGet;
exports.tableColumnPresetSave = tableColumnPresetSave;
exports.isUserColumnPresetsEnabled = isUserColumnPresetsEnabled;
const table_1 = require("../components/table");
const utils_1 = require("../utils");
async function tableColumnPresetGet(req, res) {
    const { params: { hash, ytAuthCluster }, } = req;
    try {
        const presetsConfig = checkEnabled(req);
        const columns = await (0, table_1.getColumnPreset)(presetsConfig, hash, ytAuthCluster);
        if (!columns) {
            const err = new Error(`Cannot find column-preset by the hash '${hash}'`);
            req.ctx.logError('Failed to get preset of columns', err);
            res.status(404).send((0, utils_1.prepareErrorToSend)(err));
        }
        res.status(200).send({ hash, columns });
    }
    catch (err) {
        req.ctx.logError('Failed to get preset of columns', err);
        res.status(500).send((0, utils_1.prepareErrorToSend)(err));
    }
}
async function tableColumnPresetSave(req, res) {
    const { body } = req;
    const { params: { ytAuthCluster }, } = req;
    try {
        const presetsConfig = checkEnabled(req);
        const result = await (0, table_1.saveColumnPreset)(presetsConfig, body, ytAuthCluster);
        res.status(200).send(result);
    }
    catch (err) {
        req.ctx.logError('Failed to save preset of columns', err);
        res.status(500).send((0, utils_1.prepareErrorToSend)(err));
    }
}
function checkEnabled(req) {
    const { userColumnPresets } = req.ctx.config;
    if (!userColumnPresets) {
        throw new Error("Users' table column presets are not enabled. You have to provide 'userColumnPresets' section in your config to use it.");
    }
    return userColumnPresets;
}
function isUserColumnPresetsEnabled(req) {
    return Boolean(req.ctx.config.userColumnPresets);
}
