"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TileStorage = void 0;
const core_common_1 = require("@itwin/core-common");
/** @beta */
class TileStorage {
    storage;
    constructor(storage) {
        this.storage = storage;
    }
    _transferConfigs = new Map();
    _pendingTransferConfigRequests = new Map();
    async downloadTile(tokenProps, iModelId, changesetId, treeId, contentId, guid) {
        const transferConfig = await this.getTransferConfig(tokenProps, iModelId);
        if (transferConfig === undefined)
            return undefined;
        try {
            const buffer = await this.storage.download({
                reference: (0, core_common_1.getTileObjectReference)(iModelId, changesetId, treeId, contentId, guid),
                transferConfig,
                transferType: "buffer",
            });
            return new Uint8Array(buffer); // should always be Buffer because transferType === "buffer"
        }
        catch {
            // @itwin/object-storage re-throws internal implementation-specific errors, so let's treat them all as 404 for now.
            return undefined;
        }
    }
    async getTransferConfig(tokenProps, iModelId) {
        if (this._transferConfigs.has(iModelId)) {
            const transferConfig = this._transferConfigs.get(iModelId);
            if (transferConfig === undefined)
                return undefined;
            if (transferConfig.expiration > new Date())
                return transferConfig;
            else // Refresh expired transferConfig
                return this.sendTransferConfigRequest(tokenProps, iModelId);
        }
        return this.sendTransferConfigRequest(tokenProps, iModelId);
    }
    async sendTransferConfigRequest(tokenProps, iModelId) {
        const pendingRequest = this._pendingTransferConfigRequests.get(iModelId);
        if (pendingRequest !== undefined)
            return pendingRequest;
        const request = (async () => {
            const config = await core_common_1.IModelTileRpcInterface.getClient().getTileCacheConfig(tokenProps);
            this._transferConfigs.set(iModelId, config);
            this._pendingTransferConfigRequests.delete(iModelId);
            return config;
        })();
        this._pendingTransferConfigRequests.set(iModelId, request);
        return request;
    }
}
exports.TileStorage = TileStorage;
//# sourceMappingURL=TileStorage.js.map