import { TileSetType } from '@basemaps/config';
import { Env, fsa } from '@basemaps/shared';
import { HttpHeader, LambdaHttpResponse } from '@linzjs/lambda';
import { convertRelativeUrl } from '../routes/tile.style.json.js';
import { ConfigLoader } from '../util/config.loader.js';
import { Etag } from '../util/etag.js';
import { NotFound, NotModified } from '../util/response.js';
import { Validate } from '../util/validate.js';
function tileserverUrl(tileSet, apiKey) {
    var _a;
    const host = (_a = Env.get(Env.PublicUrlBase)) !== null && _a !== void 0 ? _a : '';
    const url = `/v1/arcgis/rest/services/${tileSet}/VectorTileServer`;
    const fullUrl = new URL(fsa.join(host, url));
    fullUrl.searchParams.set('api', apiKey);
    fullUrl.searchParams.set('f', 'json');
    return fullUrl.toString().replace(/%7B/g, '{').replace(/%7D/g, '}');
}
function convertStyleJson(tileSet, style, apiKey) {
    var _a;
    const sources = JSON.parse(JSON.stringify(style.sources));
    // Only keep the vector layer and update the source url
    for (const [key, value] of Object.entries(sources)) {
        if (value.type === 'vector') {
            value.url = tileserverUrl(tileSet, apiKey);
            sources[key] = value;
        }
        else {
            delete sources[key];
        }
    }
    // Remove all the not vector layers.
    const layers = [];
    for (const layer of style.layers) {
        if (layer.source != null && !sources.hasOwnProperty(layer.source))
            continue;
        layers.push(layer);
    }
    return {
        version: 8,
        id: style.id,
        name: style.name,
        sources,
        layers,
        metadata: (_a = style.metadata) !== null && _a !== void 0 ? _a : {},
        glyphs: convertRelativeUrl(style.glyphs),
        sprite: convertRelativeUrl(style.sprite),
    };
}
export async function arcgisStyleJsonGet(req) {
    const apiKey = Validate.apiKey(req);
    const config = await ConfigLoader.load(req);
    const tileSet = await config.TileSet.get(config.TileSet.id(req.params.tileSet));
    if ((tileSet === null || tileSet === void 0 ? void 0 : tileSet.type) !== TileSetType.Vector)
        return NotFound();
    const style = req.query.get('style');
    const styleName = style ? style : 'topographic'; // Defalut to topographic style
    // Get style Config from db
    const dbId = config.Style.id(styleName);
    const styleConfig = await config.Style.get(dbId);
    if (styleConfig == null)
        return NotFound();
    // Prepare sources and add linz source
    const styleJson = convertStyleJson(tileSet.name, styleConfig.style, apiKey);
    const data = Buffer.from(JSON.stringify(styleJson));
    const cacheKey = Etag.key(data);
    if (Etag.isNotModified(req, cacheKey))
        return NotModified();
    const response = new LambdaHttpResponse(200, 'ok');
    response.header(HttpHeader.ETag, cacheKey);
    response.header(HttpHeader.CacheControl, 'no-store');
    response.buffer(data, 'application/json');
    req.set('bytes', data.byteLength);
    return response;
}
//# sourceMappingURL=arcgis.style.json.js.map