import { getOgcItemQueryParams } from "./getOgcItemQueryParams";
import { ogcApiRequest } from "./ogcApiRequest";
import { ogcItemToSearchResult } from "./ogcItemToSearchResult";
import { ogcItemToDiscussionPostResult } from "./ogcItemToDiscussionPostResult";
export const _INTERNAL_FNS = {
    searchOgcItems,
    formatOgcItemsResponse,
    formatDiscussionPostTargetEntityResponse,
    formatItemTargetEntityResponse,
    getNextOgcCallback,
};
export async function searchOgcItems(url, query, options) {
    const queryParams = getOgcItemQueryParams(query, options);
    const rawResponse = (await ogcApiRequest(url, queryParams, options));
    return _INTERNAL_FNS.formatOgcItemsResponse(rawResponse, url, query, options);
}
export async function formatOgcItemsResponse(response, url, originalQuery, originalOptions) {
    if (originalQuery.targetEntity === "discussionPost") {
        return _INTERNAL_FNS.formatDiscussionPostTargetEntityResponse(response, url, originalQuery, originalOptions);
    }
    return formatItemTargetEntityResponse(response, url, originalQuery, originalOptions);
}
export async function formatDiscussionPostTargetEntityResponse(response, url, originalQuery, originalOptions) {
    const formattedResults = await Promise.all(response.features.map((f) => ogcItemToDiscussionPostResult(f)));
    const next = _INTERNAL_FNS.getNextOgcCallback(response, url, originalQuery, originalOptions);
    const nextLink = response.links.find((l) => l.rel === "next");
    return {
        total: response.numberMatched,
        results: formattedResults,
        hasNext: !!nextLink,
        next,
    };
}
export async function formatItemTargetEntityResponse(response, url, originalQuery, originalOptions) {
    const formattedResults = await Promise.all(response.features.map((f) => ogcItemToSearchResult(f, originalOptions.include, originalOptions.requestOptions)));
    const next = _INTERNAL_FNS.getNextOgcCallback(response, url, originalQuery, originalOptions);
    const nextLink = response.links.find((l) => l.rel === "next");
    return {
        total: response.numberMatched,
        results: formattedResults,
        hasNext: !!nextLink,
        next,
    };
}
export function getNextOgcCallback(response, url, originalQuery, originalOptions) {
    const nextLink = response.links.find((l) => l.rel === "next");
    let callback = () => null;
    if (nextLink) {
        callback = () => {
            const nextUrl = new URL(nextLink.href);
            const start = +nextUrl.searchParams.get("startindex");
            const nextOptions = Object.assign(Object.assign({}, originalOptions), { start });
            return _INTERNAL_FNS.searchOgcItems(url, originalQuery, nextOptions);
        };
    }
    return callback;
}
//# sourceMappingURL=searchOgcItems.js.map