/**
 * Copyright (c) 2022
 *
 * Embed ThoughtSpot search or a saved answer
 * @summary Search embed
 * @author Ayon Ghosh <ayon.ghosh@thoughtspot.com>
 */
import { DataSourceVisualMode, Param, Action, } from '../types';
import { getQueryParamString, checkReleaseVersionInBeta, getFilterQuery, getRuntimeParameters, } from '../utils';
import { TsEmbed } from './ts-embed';
import { ERROR_MESSAGE } from '../errors';
import { getAuthPromise } from './base';
import { getReleaseVersion } from '../auth';
import { getEmbedConfig } from './embedConfig';
/**
 * Define the initial state os column custom group accordions
 * in data panel v2.
 */
export var DataPanelCustomColumnGroupsAccordionState;
(function (DataPanelCustomColumnGroupsAccordionState) {
    /**
     * Expand all the accordion initially in data panel v2.
     */
    DataPanelCustomColumnGroupsAccordionState["EXPAND_ALL"] = "EXPAND_ALL";
    /**
     * Collapse all the accordions initially in data panel v2.
     */
    DataPanelCustomColumnGroupsAccordionState["COLLAPSE_ALL"] = "COLLAPSE_ALL";
    /**
     * Expand the first accordion and collapse the rest.
     */
    DataPanelCustomColumnGroupsAccordionState["EXPAND_FIRST"] = "EXPAND_FIRST";
})(DataPanelCustomColumnGroupsAccordionState || (DataPanelCustomColumnGroupsAccordionState = {}));
export const HiddenActionItemByDefaultForSearchEmbed = [
    Action.EditACopy,
    Action.SaveAsView,
    Action.UpdateTML,
    Action.EditTML,
    Action.AnswerDelete,
];
/**
 * Embed ThoughtSpot search
 * @group Embed components
 */
export class SearchEmbed extends TsEmbed {
    constructor(domSelector, viewConfig) {
        viewConfig.embedComponentType = 'SearchEmbed';
        super(domSelector, viewConfig);
    }
    /**
     * Get the state of the data sources panel that the embedded
     * ThoughtSpot search will be initialized with.
     */
    getDataSourceMode() {
        let dataSourceMode = DataSourceVisualMode.Expanded;
        if (this.viewConfig.collapseDataSources === true
            || this.viewConfig.collapseDataPanel === true) {
            dataSourceMode = DataSourceVisualMode.Collapsed;
        }
        if (this.viewConfig.hideDataSources === true) {
            dataSourceMode = DataSourceVisualMode.Hidden;
        }
        return dataSourceMode;
    }
    getSearchInitData() {
        var _a;
        return {
            ...(this.viewConfig.excludeSearchTokenStringFromURL ? {
                searchOptions: {
                    searchTokenString: (_a = this.viewConfig.searchOptions) === null || _a === void 0 ? void 0 : _a.searchTokenString,
                },
            } : {}),
        };
    }
    async getAppInitData() {
        const defaultAppInitData = await super.getAppInitData();
        return { ...defaultAppInitData, ...this.getSearchInitData() };
    }
    getEmbedParams() {
        var _a;
        const { hideResults, enableSearchAssist, forceTable, searchOptions, runtimeFilters, dataSource, dataSources, excludeRuntimeFiltersfromURL, hideSearchBar, dataPanelV2 = false, useLastSelectedSources = false, runtimeParameters, collapseSearchBarInitially = false, enableCustomColumnGroups = false, isOnBeforeGetVizDataInterceptEnabled = false, 
        /* eslint-disable-next-line max-len */
        dataPanelCustomGroupsAccordionInitialState = DataPanelCustomColumnGroupsAccordionState.EXPAND_ALL, focusSearchBarOnRender = true, excludeRuntimeParametersfromURL, excludeSearchTokenStringFromURL, collapseSearchBar = true, } = this.viewConfig;
        const queryParams = this.getBaseQueryParams();
        queryParams[Param.HideActions] = [
            ...((_a = queryParams[Param.HideActions]) !== null && _a !== void 0 ? _a : []),
            ...HiddenActionItemByDefaultForSearchEmbed,
        ];
        if (dataSources && dataSources.length) {
            queryParams[Param.DataSources] = JSON.stringify(dataSources);
        }
        if (dataSource) {
            queryParams[Param.DataSources] = `["${dataSource}"]`;
        }
        if (searchOptions === null || searchOptions === void 0 ? void 0 : searchOptions.searchTokenString) {
            if (!excludeSearchTokenStringFromURL) {
                queryParams[Param.searchTokenString] = encodeURIComponent(searchOptions.searchTokenString);
            }
            if (searchOptions.executeSearch) {
                queryParams[Param.executeSearch] = true;
            }
        }
        if (enableSearchAssist) {
            queryParams[Param.EnableSearchAssist] = true;
        }
        if (hideResults) {
            queryParams[Param.HideResult] = true;
        }
        if (forceTable) {
            queryParams[Param.ForceTable] = true;
        }
        if (hideSearchBar) {
            queryParams[Param.HideSearchBar] = true;
        }
        if (isOnBeforeGetVizDataInterceptEnabled) {
            /* eslint-disable-next-line max-len */
            queryParams[Param.IsOnBeforeGetVizDataInterceptEnabled] = isOnBeforeGetVizDataInterceptEnabled;
        }
        if (!focusSearchBarOnRender) {
            queryParams[Param.FocusSearchBarOnRender] = focusSearchBarOnRender;
        }
        queryParams[Param.DataPanelV2Enabled] = dataPanelV2;
        queryParams[Param.DataSourceMode] = this.getDataSourceMode();
        queryParams[Param.UseLastSelectedDataSource] = useLastSelectedSources;
        if (dataSource || dataSources) {
            queryParams[Param.UseLastSelectedDataSource] = false;
        }
        queryParams[Param.searchEmbed] = true;
        /* eslint-disable-next-line max-len */
        queryParams[Param.CollapseSearchBarInitially] = collapseSearchBarInitially || collapseSearchBar;
        queryParams[Param.EnableCustomColumnGroups] = enableCustomColumnGroups;
        if (dataPanelCustomGroupsAccordionInitialState
            === DataPanelCustomColumnGroupsAccordionState.COLLAPSE_ALL
            || dataPanelCustomGroupsAccordionInitialState
                === DataPanelCustomColumnGroupsAccordionState.EXPAND_FIRST) {
            /* eslint-disable-next-line max-len */
            queryParams[Param.DataPanelCustomGroupsAccordionInitialState] = dataPanelCustomGroupsAccordionInitialState;
        }
        else {
            /* eslint-disable-next-line max-len */
            queryParams[Param.DataPanelCustomGroupsAccordionInitialState] = DataPanelCustomColumnGroupsAccordionState.EXPAND_ALL;
        }
        let query = '';
        const queryParamsString = getQueryParamString(queryParams, true);
        if (queryParamsString) {
            query = `?${queryParamsString}`;
        }
        const parameterQuery = getRuntimeParameters(runtimeParameters || []);
        if (parameterQuery && !excludeRuntimeParametersfromURL)
            query += `&${parameterQuery}`;
        const filterQuery = getFilterQuery(runtimeFilters || []);
        if (filterQuery && !excludeRuntimeFiltersfromURL) {
            query += `&${filterQuery}`;
        }
        return query;
    }
    /**
     * Construct the URL of the embedded ThoughtSpot search to be
     * loaded in the iframe
     * @param answerId The GUID of a saved answer
     * @param dataSources A list of data source GUIDs
     */
    getIFrameSrc() {
        const { answerId } = this.viewConfig;
        const answerPath = answerId ? `saved-answer/${answerId}` : 'answer';
        const tsPostHashParams = this.getThoughtSpotPostUrlParams();
        return `${this.getRootIframeSrc()}/embed/${answerPath}${tsPostHashParams}`;
    }
    /**
     * Render the embedded ThoughtSpot search
     */
    async render() {
        await super.render();
        const { answerId } = this.viewConfig;
        const src = this.getIFrameSrc();
        await this.renderIFrame(src);
        getAuthPromise().then(() => {
            if (checkReleaseVersionInBeta(getReleaseVersion(), getEmbedConfig().suppressSearchEmbedBetaWarning
                || getEmbedConfig().suppressErrorAlerts)) {
                alert(ERROR_MESSAGE.SEARCHEMBED_BETA_WRANING_MESSAGE);
            }
        });
        return this;
    }
}
//# sourceMappingURL=search.js.map