"use strict";
// Copyright (c) Microsoft. All rights reserved.
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var sp_core_library_1 = require("@microsoft/sp-core-library");
var sp_http_1 = require("@microsoft/sp-http");
var NavigationDataError_1 = tslib_1.__importStar(require("./NavigationDataError"));
/**
 * Navigation Data Provider for SPFx applications.
 * It fetches data required to initiate an SPFx Navigation operation. It also caches the navigation
 * data when appropriate
 *
 * @internal
 */
var NavigationDataProvider = /** @class */ (function () {
    function NavigationDataProvider(serviceScope, validator) {
        sp_core_library_1.Validate.isNotNullOrUndefined(serviceScope, 'serviceScope');
        sp_core_library_1.Validate.isNotNullOrUndefined(validator, 'validator');
        this._spHttpClient = serviceScope.consume(sp_http_1.SPHttpClient.serviceKey);
        this._dataValidator = validator;
    }
    Object.defineProperty(NavigationDataProvider.prototype, "buildId", {
        get: function () {
            return this._buildId;
        },
        /**
         * Keeps track of the build id the application is bootstrapped with.
         * Used to detect when the build id change while the app is
         * running, and to invalidate manifest caches containing the old build id.
         *
         * @param buildId - Build id the application was bootstrapped with.
         */
        set: function (buildId) {
            this._buildId = buildId;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Issues a request to get data association with a given url
     *
     * @param url - URL of the page to fetch data for
     * @param requestType - The request type
     * @param props - Optional Navigation property bag
     *
     * @returns - A navigation data response promise
     */
    NavigationDataProvider.prototype.getData = function (url, props) {
        sp_core_library_1.Validate.isNonemptyString(url, 'url');
        return this._getStore().then(function (store) { return store.getData(url, props); });
    };
    /**
     * Invalidates a cached resource by its URL. Any subsequent request for the resource
     * will be fetched from its origin and recached.
     *
     * @param url - URL to invalidate
     */
    NavigationDataProvider.prototype.invalidate = function (url) {
        return this._getStore().then(function (store) {
            store.remove(url);
        });
    };
    NavigationDataProvider.prototype._getStore = function () {
        var _this = this;
        if (this._navigationStore) {
            return Promise.resolve(this._navigationStore);
        }
        return (this._navigationStorePromise ||
            (this._navigationStorePromise = Promise.resolve().then(function () { return tslib_1.__importStar(require('./NavigationDataStore' /* webpackChunkName: 'sp-navigation-datastore' */)); }).then(function (dataStore) {
                _this._navigationStore = new dataStore.default(NavigationDataProvider.storeKey, NavigationDataProvider.storeBuildIdKey, _this._buildId, function (url, headers) {
                    return _this._fetchData(url, headers);
                }, _this._dataValidator);
                return _this._navigationStore;
            })));
    };
    /**
     * Loads a page from SharePoint.
     *
     * @param url - URL of the page to load.
     * @param requestHeaders - Optional request headers
     * @return Promise with the pertinent data for the request.
     */
    NavigationDataProvider.prototype._fetchData = function (url, requestHeaders) {
        var hashFragmentInUrlKSActivated = sp_core_library_1._SPKillSwitch.isActivated('839bbdd6-40d5-40f7-8193-5a0641f1e6bb'
        /* '02/22/2021', 'Discard hash fragment from the url' */
        );
        var urlToLoad = !hashFragmentInUrlKSActivated ? url.split('#')[0] : url;
        // Using ?as=json to ensure that the browser doesn't return a cached request for the HTML
        return this._spHttpClient
            .get(urlToLoad + (urlToLoad.indexOf('?') === -1 ? '?' : '&') + 'as=json', sp_http_1.SPHttpClient.configurations.v1, requestHeaders ? { headers: requestHeaders } : undefined)
            .then(function (response) {
            if (!response.ok) {
                throw NavigationDataError_1.default.createNavigationError(NavigationDataError_1.NavigationErrorCode.fetchData, new Error(response.statusMessage));
            }
            else {
                return response.json().catch(function (error) {
                    throw NavigationDataError_1.default.createNavigationError(NavigationDataError_1.NavigationErrorCode.parseData, error);
                });
            }
        });
    };
    NavigationDataProvider.storeKey = 'sp-application-base:NavigationDataStore';
    NavigationDataProvider.storeBuildIdKey = 'sp-application-base:NavigationDataStore:buildId';
    return NavigationDataProvider;
}());
exports.default = NavigationDataProvider;
//# sourceMappingURL=NavigationDataProvider.js.map