"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var sp_core_library_1 = require("@microsoft/sp-core-library");
var sp_diagnostics_1 = require("@microsoft/sp-diagnostics");
var sp_loader_1 = require("@microsoft/sp-loader");
var CustomActionLocations_1 = tslib_1.__importDefault(require("./customAction/CustomActionLocations"));
/**
 * Search query manager is used to get the search query in SPFx.
 * It supports Search query modifier extensions that can enrich the search query, and supports cases where the user
 * comes from classic pages to modern.
 *
 * @internal
 */
var SearchQueryManager = /** @class */ (function () {
    function SearchQueryManager(serviceScope) {
        this._isInitialized = false;
        this._areExtensionsLoaded = false;
        this._serviceScope = serviceScope;
    }
    SearchQueryManager.prototype.initialize = function (preloadedData, updateSearchBoxText) {
        this._preloadedData = preloadedData;
        this._updateSearchBoxText = updateSearchBoxText;
        var queryParameters = new URL(window.location.href).searchParams;
        this._isInitialized = false;
        this._areExtensionsLoaded = false;
        var searchQuery = this._getUrlSearchQuery(queryParameters);
        if (searchQuery && this._hasExtensions(queryParameters)) {
            return this._initializeExtensions('initialize');
        }
        else {
            this._isInitialized = true;
            this._areExtensionsLoaded = false;
            return Promise.resolve();
        }
    };
    /**
     * Update SearchQueryManager from location
     * @param queryString - next querystring
     */
    SearchQueryManager.prototype.updateFromQueryString = function (queryString) {
        var queryParameters = new URLSearchParams(queryString.substring(1));
        var searchQuery = this._getUrlSearchQuery(queryParameters);
        if (searchQuery && this._updateSearchBoxText) {
            this._updateSearchBoxText(this._serviceScope, searchQuery);
        }
        if (searchQuery && this._hasExtensions(queryParameters) && !this._areExtensionsLoaded) {
            return this._initializeExtensions('update');
        }
        else {
            return Promise.resolve();
        }
    };
    SearchQueryManager.prototype.isInitialized = function () {
        return this._isInitialized;
    };
    /**
     * Get the search query from the current URL.
     */
    SearchQueryManager.prototype.getSearchData = function () {
        if (!this._isInitialized) {
            return Promise.reject(new Error('SearchQueryManager is not initialized'));
        }
        var shouldAddScopeToSearch = !sp_core_library_1._SPKillSwitch.isActivated('c55b73f2-1ec7-453a-a41e-e21131206fd1' /* '03/03/2021', 'Add scope to search dynamic data' */) &&
            (sp_core_library_1._SPFlight.isEnabled(1534 /*CSISpoScopeControl*/) ||
                sp_core_library_1._SPExperiment.getVariantAndLogExposure(90097 /*CSISpoScopeControlExperiment*/) === 1);
        var queryParameters = new URL(window.location.href).searchParams;
        var searchQuery = this._getUrlSearchQuery(queryParameters);
        var searchScope;
        if (shouldAddScopeToSearch) {
            searchScope = this._getUrlSearchScope(queryParameters);
        }
        if (searchQuery && this._hasExtensions(queryParameters)) {
            var qosMonitor_1 = new sp_diagnostics_1._QosMonitor('SearchQueryManager.getSearchData');
            return this._getExtensionManager()
                .then(function (extensionManager) { return extensionManager.getSearchQuery(searchQuery); })
                .then(function (q) {
                qosMonitor_1.writeSuccess();
                return shouldAddScopeToSearch ? { searchQuery: q, searchScope: searchScope } : { searchQuery: q };
            })
                .catch(function (e) {
                qosMonitor_1.writeUnexpectedFailure(undefined, e);
                throw e;
            });
        }
        else {
            return Promise.resolve(shouldAddScopeToSearch ? { searchQuery: searchQuery, searchScope: searchScope } : { searchQuery: searchQuery });
        }
    };
    SearchQueryManager.prototype._getUrlSearchQuery = function (searchParams) {
        // If ?q is not present, ?k can be used (support cases coming from classic pages)
        return searchParams.get('q') || searchParams.get('k') || undefined;
    };
    SearchQueryManager.prototype._getUrlSearchScope = function (searchParams) {
        return searchParams.get('scope') || undefined;
    };
    /**
     * Returns true if there is any SearchQueryModifier extension.
     * When using query params, it just checks if there is any custom action regardless of type.
     * This is exclusively a debug scenario and it's faster and smaller code, considering this runs in a core scenario.
     */
    SearchQueryManager.prototype._hasExtensions = function (searchParams) {
        return (searchParams.has('customActions') ||
            (!!this._preloadedData.customActions &&
                this._preloadedData.customActions.some(function (customAction) { return customAction.location === CustomActionLocations_1.default.SEARCH_QUERY_MODIFIER; })));
    };
    SearchQueryManager.prototype._getExtensionManager = function () {
        var _this = this;
        if (!this._extensionManagerPromise) {
            this._extensionManagerPromise = sp_loader_1.SPComponentLoader.loadComponentById('4958ea79-6ff3-4480-8291-0932dd010869').then(function (spSearchExtensibility) {
                return new spSearchExtensibility._SearchQueryExtensionManager(_this._serviceScope);
            });
        }
        return this._extensionManagerPromise;
    };
    SearchQueryManager.prototype._initializeExtensions = function (qosAction) {
        var _this = this;
        var qosMonitor = new sp_diagnostics_1._QosMonitor('SearchQueryManager.' + qosAction);
        return this._getExtensionManager()
            .then(function (extensionManager) {
            return extensionManager
                .initializeExtensions(_this._preloadedData.customActions)
                .then(function (numberOfExtensions) {
                _this._areExtensionsLoaded = true;
                _this._isInitialized = true;
                qosMonitor.writeSuccess({ numberOfExtensions: numberOfExtensions });
            });
        })
            .catch(function (e) {
            qosMonitor.writeUnexpectedFailure(undefined, e, { numberOfExtensions: 0 });
            throw e;
        });
    };
    SearchQueryManager.serviceKey = sp_core_library_1.ServiceKey.create('sp-application-base:SearchQueryManager', SearchQueryManager);
    return SearchQueryManager;
}());
exports.default = SearchQueryManager;
//# sourceMappingURL=SearchQueryManager.js.map