"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Views
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApproximateTerrainHeights = void 0;
const core_bentley_1 = require("@itwin/core-bentley");
const core_geometry_1 = require("@itwin/core-geometry");
const core_common_1 = require("@itwin/core-common");
const internal_1 = require("./tile/internal");
let instance;
/**
 * A collection of functions for approximating terrain height
 * @internal
 */
class ApproximateTerrainHeights {
    constructor() {
        this.globalHeightRange = core_geometry_1.Range1d.createXX(-400, 90000); // Dead Sea to Mount Everest.
        this._scratchCorners = [core_common_1.Cartographic.createZero(), core_common_1.Cartographic.createZero(), core_common_1.Cartographic.createZero(), core_common_1.Cartographic.createZero()];
        this._tilingScheme = new internal_1.GeographicTilingScheme(2, 1, true); // Y at top... ?
        this._scratchTileXY = core_geometry_1.Point2d.createZero();
    }
    static get instance() {
        if (undefined === instance)
            instance = new ApproximateTerrainHeights();
        return instance;
    }
    /**
     * Initializes the minimum and maximum terrain heights.
     * @return {Promise}
     */
    async initialize() {
        if (!this._terrainHeights) {
            const { terrainHeightsPropsString } = await Promise.resolve().then(() => __importStar(require("./ApproximateTerrainHeightsProps")));
            this._terrainHeights = JSON.parse(terrainHeightsPropsString);
        }
    }
    getTileHeightRange(quadId, result) {
        result = core_geometry_1.Range1d.createFrom(this.globalHeightRange, result);
        if (undefined === this._terrainHeights)
            return result; // Not initialized.
        let level = quadId.level, column = quadId.column, row = quadId.row;
        if (level > 6) {
            column = column >> (level - 6);
            row = row >> quadId.row >> ((level - 6));
            level = 6;
        }
        const key = `${level}-${column}-${row}`;
        const heights = this._terrainHeights[key];
        (0, core_bentley_1.assert)(undefined !== heights);
        result.low = heights[0];
        result.high = heights[1];
        return result;
    }
    getMinimumMaximumHeights(rectangle, result) {
        result = core_geometry_1.Range1d.createFrom(this.globalHeightRange, result);
        if (undefined === this._terrainHeights)
            return result; // Not initialized.
        const xyLevel = this._getTileXYLevel(rectangle);
        if (undefined !== xyLevel) {
            const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
            const heights = this._terrainHeights[key];
            (0, core_bentley_1.assert)(undefined !== heights);
            if (undefined !== heights) {
                result.low = heights[0];
                result.high = heights[1];
            }
        }
        return result;
    }
    _getTileXYLevel(rectangle) {
        core_common_1.Cartographic.fromRadians({ longitude: rectangle.low.x, latitude: rectangle.high.y, height: 0.0 }, this._scratchCorners[0]);
        core_common_1.Cartographic.fromRadians({ longitude: rectangle.high.x, latitude: rectangle.high.y, height: 0.0 }, this._scratchCorners[1]);
        core_common_1.Cartographic.fromRadians({ longitude: rectangle.low.x, latitude: rectangle.low.y, height: 0.0 }, this._scratchCorners[2]);
        core_common_1.Cartographic.fromRadians({ longitude: rectangle.high.x, latitude: rectangle.low.y, height: 0.0 }, this._scratchCorners[3]);
        // Determine which tile the bounding rectangle is in
        let lastLevelX = 0, lastLevelY = 0;
        let currentX = 0, currentY = 0;
        const maxLevel = ApproximateTerrainHeights.maxLevel;
        let i;
        for (i = 0; i <= maxLevel; ++i) {
            let failed = false;
            for (let j = 0; j < 4; ++j) {
                const corner = this._scratchCorners[j];
                this._tilingScheme.cartographicToTileXY(corner, i, this._scratchTileXY);
                if (j === 0) {
                    currentX = this._scratchTileXY.x;
                    currentY = this._scratchTileXY.y;
                }
                else if (currentX !== this._scratchTileXY.x || currentY !== this._scratchTileXY.y) {
                    failed = true;
                    break;
                }
            }
            if (failed)
                break;
            lastLevelX = currentX;
            lastLevelY = currentY;
        }
        if (i === 0) {
            return undefined;
        }
        return {
            x: lastLevelX,
            y: lastLevelY,
            level: (i > maxLevel) ? maxLevel : (i - 1),
        };
    }
}
exports.ApproximateTerrainHeights = ApproximateTerrainHeights;
ApproximateTerrainHeights.maxLevel = 6;
//# sourceMappingURL=ApproximateTerrainHeights.js.map