"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RealityDataSourceCesiumIonAssetImpl = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Tiles
 */
const Request_1 = require("./request/Request");
const core_bentley_1 = require("@itwin/core-bentley");
const core_common_1 = require("@itwin/core-common");
const internal_1 = require("./tile/internal");
/** This class provides access to the reality data provider services.
 * It encapsulates access to a reality data weiter it be from local access, http or ProjectWise Context Share.
 * The key provided at the creation determines if this is ProjectWise Context Share reference.
 * If not then it is considered local (ex: C:\temp\TileRoot.json) or plain http access (http://someserver.com/data/TileRoot.json)
 * There is a one to one relationship between a reality data and the instances of present class.
* @internal
*/
class RealityDataSourceCesiumIonAssetImpl {
    /** Construct a new reality data source.
     * @param props JSON representation of the reality data source
     */
    constructor(props) {
        /** For use by all Reality Data. For RD stored on PW Context Share, represents the portion from the root of the Azure Blob Container*/
        this._baseUrl = "";
        (0, core_bentley_1.assert)(props.sourceKey.provider === core_common_1.RealityDataProvider.CesiumIonAsset);
        this.key = props.sourceKey;
    }
    /**
     * Create an instance of this class from a source key and iTwin context/
     */
    static async createFromKey(sourceKey, iTwinId) {
        if (sourceKey.provider !== core_common_1.RealityDataProvider.CesiumIonAsset)
            return undefined;
        const rdSource = new RealityDataSourceCesiumIonAssetImpl({ sourceKey });
        let tilesetUrl;
        try {
            tilesetUrl = await rdSource.getServiceUrl(iTwinId);
        }
        catch { }
        return (tilesetUrl !== undefined) ? rdSource : undefined;
    }
    get isContextShare() {
        return false;
    }
    /**
     * Returns Reality Data if available
    */
    get realityData() {
        return undefined;
    }
    get realityDataId() {
        return undefined;
    }
    /**
     * Returns Reality Data type if available
     */
    get realityDataType() {
        return undefined;
    }
    // This is to set the root url from the provided root document path.
    // If the root document is stored on PW Context Share then the root document property of the Reality Data is provided,
    // otherwise the full path to root document is given.
    // The base URL contains the base URL from which tile relative path are constructed.
    // The tile's path root will need to be reinserted for child tiles to return a 200
    setBaseUrl(url) {
        const urlParts = url.split("/");
        urlParts.pop();
        if (urlParts.length === 0)
            this._baseUrl = "";
        else
            this._baseUrl = `${urlParts.join("/")}/`;
    }
    /**
     * This method returns the URL to access the actual 3d tiles from the service provider.
     * @returns string containing the URL to reality data.
     */
    async getServiceUrl(_iTwinId) {
        // If url was not resolved - resolve it
        this._tilesetUrl = this.key.id;
        if (this.key.id === internal_1.CesiumIonAssetProvider.osmBuildingId) {
            this._tilesetUrl = (0, internal_1.getCesiumOSMBuildingsUrl)();
        }
        else {
            const parsedId = internal_1.CesiumIonAssetProvider.parseCesiumUrl(this.key.id);
            if (parsedId) {
                this._tilesetUrl = (0, internal_1.getCesiumAssetUrl)(parsedId.id, parsedId.key);
            }
        }
        return this._tilesetUrl;
    }
    async getRootDocument(iTwinId) {
        let url = await this.getServiceUrl(iTwinId);
        if (!url)
            throw new core_common_1.IModelError(core_bentley_1.BentleyStatus.ERROR, "Unable to get service url");
        // The following is only if the reality data is not stored on PW Context Share.
        const cesiumAsset = internal_1.CesiumIonAssetProvider.parseCesiumUrl(url);
        if (cesiumAsset) {
            const tokenAndUrl = await (0, internal_1.getCesiumAccessTokenAndEndpointUrl)(`${cesiumAsset.id}`, cesiumAsset.key);
            if (tokenAndUrl.url && tokenAndUrl.token) {
                url = tokenAndUrl.url;
                this._requestAuthorization = `Bearer ${tokenAndUrl.token}`;
            }
        }
        // The following is only if the reality data is not stored on PW Context Share.
        this.setBaseUrl(url);
        const headers = { authorization: this._requestAuthorization };
        return (0, Request_1.request)(url, "json", { headers });
    }
    /**
     * Returns the tile content. The path to the tile is relative to the base url of present reality data whatever the type.
     */
    async getTileContent(name) {
        const tileUrl = this._baseUrl + name;
        const headers = { authorization: this._requestAuthorization };
        return (0, Request_1.request)(tileUrl, "arraybuffer", { headers });
    }
    /**
     * Returns the tile content in json format. The path to the tile is relative to the base url of present reality data whatever the type.
     */
    async getTileJson(name) {
        const tileUrl = this._baseUrl + name;
        const headers = { authorization: this._requestAuthorization };
        return (0, Request_1.request)(tileUrl, "json", { headers });
    }
    getTileContentType(url) {
        return url.endsWith("json") ? "tileset" : "tile";
    }
    /**
     * Gets spatial location and extents of this reality data source
     * @returns spatial location and extents
     * @internal
     */
    async getSpatialLocationAndExtents() {
        // Cesium Ion asset we currenlty support are unbound (cover all earth)
        const spatialLocation = undefined;
        return spatialLocation;
    }
    /**
     * Gets information to identify the product and engine that create this reality data
     * Will return undefined if cannot be resolved
     * @returns information to identify the product and engine that create this reality data
     * @alpha
     */
    async getPublisherProductInfo() {
        let publisherInfo;
        return publisherInfo;
    }
}
exports.RealityDataSourceCesiumIonAssetImpl = RealityDataSourceCesiumIonAssetImpl;
//# sourceMappingURL=RealityDataSourceCesiumIonAssetImpl.js.map