import { GoogleTms, ImageFormat } from '@basemaps/geo';
import { Config } from './config.js';
import { toQueryString } from '@basemaps/shared/build/url.js';
import { isBase58, base58 } from '@basemaps/config/build/base58.js';
export function ensureBase58(s) {
    if (s == null)
        return null;
    if (isBase58(s))
        return s;
    const text = new TextEncoder();
    const buffer = text.encode(s);
    return base58.encode(buffer);
}
export const WindowUrl = {
    ImageFormat: 'png',
    /**
     * Encode a location into the window.hash
     * Google uses ${lat},${lon},z${zoom}
     * TODO do we want to follow this
     */
    toHash(loc) {
        return `#@${loc.lat.toFixed(7)},${loc.lon.toFixed(7)},z${loc.zoom}`;
    },
    /**
     * Support parsing of zooms with `z14` or `14z`
     * @param zoom string to parse zoom from
     */
    parseZoom(zoom) {
        if (zoom == null || zoom === '')
            return NaN;
        if (zoom.startsWith('z'))
            return parseFloat(zoom.slice(1));
        if (zoom.endsWith('z'))
            return parseFloat(zoom);
        return NaN;
    },
    /** Parse a location from window.hash if it exists */
    fromHash(str) {
        const output = {};
        const hash = str.replace('#@', '');
        const [latS, lonS, zoomS] = hash.split(',');
        const lat = parseFloat(latS);
        const lon = parseFloat(lonS);
        if (!isNaN(lat) && !isNaN(lon)) {
            output.lat = lat;
            output.lon = lon;
        }
        const newZoom = WindowUrl.parseZoom(zoomS);
        if (!isNaN(newZoom)) {
            output.zoom = newZoom;
        }
        return output;
    },
    baseUrl() {
        const baseUrl = Config.BaseUrl;
        if (baseUrl === '')
            return window.location.origin;
        if (!baseUrl.startsWith('http'))
            throw new Error('BaseURL must start with http(s)://');
        return baseUrl;
    },
    toBaseWmts() {
        const query = toQueryString({ api: Config.ApiKey, config: ensureBase58(Config.map.config) });
        return `${this.baseUrl()}/v1/tiles/aerial/WMTSCapabilities.xml${query}`;
    },
    toImageryUrl(layerId, imageryType) {
        return `${this.baseUrl()}/v1/imagery/${layerId}/${imageryType}`;
    },
    toTileUrl(urlType, tileMatrix, layerId, style, config) {
        const queryParams = new URLSearchParams();
        if (Config.ApiKey != null && Config.ApiKey !== '')
            queryParams.set('api', Config.ApiKey);
        if (config != null)
            queryParams.set('config', ensureBase58(config));
        if (urlType === "style" /* MapOptionType.Style */) {
            if (tileMatrix.identifier !== GoogleTms.identifier)
                queryParams.set('tileMatrix', tileMatrix.identifier);
            if (WindowUrl.ImageFormat !== ImageFormat.Webp)
                queryParams.set('format', WindowUrl.ImageFormat);
        }
        const q = '?' + queryParams.toString();
        const baseTileUrl = `${this.baseUrl()}/v1/tiles/${layerId}/${tileMatrix.identifier}`;
        if (urlType === "raster" /* MapOptionType.TileRaster */)
            return `${baseTileUrl}/{z}/{x}/{y}.${WindowUrl.ImageFormat}${q}`;
        if (urlType === "vector-xyz" /* MapOptionType.TileVectorXyz */)
            return `${baseTileUrl}/{z}/{x}/{y}.pbf${q}`;
        if (urlType === "style" /* MapOptionType.Style */)
            return `${this.baseUrl()}/v1/styles/${style !== null && style !== void 0 ? style : layerId}.json${q}`;
        if (urlType === "wmts" /* MapOptionType.Wmts */)
            return `${baseTileUrl}/WMTSCapabilities.xml${q}`;
        if (urlType === "attribution" /* MapOptionType.Attribution */)
            return `${baseTileUrl}/attribution.json${q}`;
        if (urlType === "tile-wmts" /* MapOptionType.TileWmts */) {
            return `${baseTileUrl}/{TileMatrix}/{TileCol}/{TileRow}.${WindowUrl.ImageFormat}${q}`;
        }
        throw new Error('Unknown url type: ' + urlType);
    },
    toConfigUrl(layerId, config = Config.map.config) {
        const query = toQueryString({ api: Config.ApiKey, config });
        return `${this.baseUrl()}/v1/config/${layerId}.json${query}`;
    },
    toConfigImageryUrl(layerId, imageryId, config = Config.map.config) {
        const query = toQueryString({ api: Config.ApiKey, config });
        return `${this.baseUrl()}/v1/config/${layerId}/${imageryId}.json${query}`;
    },
};
//# sourceMappingURL=url.js.map