"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.homeIndexFactory = homeIndexFactory;
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const layout_config_1 = require("../components/layout-config");
const settings_1 = require("../components/settings");
const utils_1 = require("../components/utils");
const ServerFactory_1 = __importDefault(require("../ServerFactory"));
const utils_2 = require("../utils");
const default_settings_1 = require("../utils/default-settings");
const is_root_page_1 = require("../utils/is-root-page");
function homeIndexFactory(entryName = 'main') {
    return async (req, res) => {
        const isRoot = (0, is_root_page_1.isRootPage)(req, req.params.ytAuthCluster);
        const cluster = isRoot ? undefined : req.params.ytAuthCluster;
        try {
            const url = await ServerFactory_1.default.getHomeRedirectedUrl(cluster, req);
            if (url) {
                return res.redirect(url);
            }
        }
        catch (e) {
            req.ctx.logError('Failed to calculate redirects', e);
        }
        const { ctx } = req;
        const { clusterConfig, ytConfig } = (0, utils_1.getClusterConfig)(cluster);
        const login = ytConfig.isLocalCluster ? 'root' : req.yt?.login;
        // Refuse to serve localRemoteProxy requests erroneously delegated from main interface to another
        // interface running in a container (instead of YT container)
        if ((0, isEmpty_1.default)(clusterConfig) && cluster) {
            if (!req.ctx.config.ytAllowRemoteLocalProxy && !(0, utils_2.isLocalModeByEnvironment)()) {
                res.redirect('/');
                return;
            }
            res.status(404).send(`No config for cluster <b>${encodeURIComponent(cluster)}</b> exists.` +
                '<div>If you are trying to connect to your local cluster please make sure:</div>' +
                '<ol><li>FQDN of the cluster is correct</li>' +
                '<li>The port is greater than or equal to 1000.</li></ol>');
            return;
        }
        const useRemoteSettings = (0, settings_1.isRemoteSettingsConfigured)();
        const settings = {
            data: (0, default_settings_1.getDefaultUserSettings)(req.ctx.config),
            meta: {
                useRemoteSettings,
                errorMessage: undefined,
            },
        };
        const settingsConfig = (0, settings_1.getSettingsConfig)(cluster);
        if (login && useRemoteSettings && settingsConfig.cluster) {
            try {
                await (0, settings_1.create)({ ctx, username: login, cluster: settingsConfig.cluster });
                const userSettings = login
                    ? await (0, settings_1.get)({ ctx, username: login, cluster: settingsConfig.cluster })
                    : {};
                settings.data = { ...settings.data, ...userSettings };
            }
            catch (e) {
                const message = `Error in getting user settings for ${login}`;
                req.ctx.logError(message, e);
                const errorMessage = `Oh, no. ${message}. You are using default settings. ` +
                    'All settings changes will be saved in browser only.\n' +
                    'Try to reload page. If problem persists please report it via Bug Reporter.';
                settings.meta = {
                    ...settings.meta,
                    useRemoteSettings: false,
                    errorMessage,
                };
            }
        }
        const layoutConfig = await (0, layout_config_1.getLayoutConfig)(req, {
            name: entryName,
            login,
            uid: req.yt?.uid,
            cluster,
            ytConfig,
            settings,
        });
        const html = await ServerFactory_1.default.renderLayout(layoutConfig, req, res);
        res.send(html);
    };
}
