import { GoogleTms, TileMatrixSet } from '@basemaps/geo';
import { Env, toQueryString } from '@basemaps/shared';
import { HttpHeader, LambdaHttpResponse } from '@linzjs/lambda';
import { ConfigLoader } from '../util/config.loader.js';
import { NotFound } from '../util/response.js';
import { Validate } from '../util/validate.js';
export async function tileJsonGet(req) {
    var _a, _b, _c, _d;
    const tileMatrix = Validate.getTileMatrixSet(req.params.tileMatrix);
    if (tileMatrix == null)
        return NotFound();
    const apiKey = Validate.apiKey(req);
    const config = await ConfigLoader.load(req);
    req.timer.start('tileset:load');
    const tileSet = await config.TileSet.get(config.TileSet.id(req.params.tileSet));
    req.timer.end('tileset:load');
    if (tileSet == null)
        return NotFound();
    const format = (_a = Validate.getRequestedFormats(req)) !== null && _a !== void 0 ? _a : [tileSet.format];
    const host = (_b = Env.get(Env.PublicUrlBase)) !== null && _b !== void 0 ? _b : '';
    const configLocation = ConfigLoader.extract(req);
    const query = toQueryString({ api: apiKey, config: configLocation });
    const tileUrl = [host, 'v1', 'tiles', tileSet.name, tileMatrix.identifier, '{z}', '{x}', '{y}'].join('/') + `.${format[0]}${query}`;
    const tileJson = { tiles: [tileUrl], tilejson: '3.0.0' };
    const maxZoom = TileMatrixSet.convertZoomLevel((_c = tileSet.maxZoom) !== null && _c !== void 0 ? _c : 30, GoogleTms, tileMatrix, true);
    const minZoom = TileMatrixSet.convertZoomLevel((_d = tileSet.minZoom) !== null && _d !== void 0 ? _d : 0, GoogleTms, tileMatrix, true);
    if (tileSet.maxZoom)
        tileJson.maxzoom = maxZoom;
    if (tileSet.minZoom)
        tileJson.minzoom = minZoom;
    const json = JSON.stringify(tileJson);
    const data = Buffer.from(json);
    const response = new LambdaHttpResponse(200, 'ok');
    response.header(HttpHeader.CacheControl, 'no-store');
    response.buffer(data, 'application/json');
    req.set('bytes', data.byteLength);
    return response;
}
//# sourceMappingURL=tile.json.js.map