Source: modules/WMS.js

/**
 * @module modules/WMS.js
 * @name WMS
 * @copyright 2023 3Liz
 * @license MPL-2.0
 */

import { Utils } from './Utils.js';
import { createEnum } from './utils/Enums.js';
import { deepFreeze } from './config/Tools.js';
import { RequestError } from './Errors.js';

/**
 * Enum for static WMS GetMap parameters
 * WMS GetMap parameters that does not change between requests
 * @enum {string}
 * @property {string} FORMAT - the WMS GetMap format parameter
 * @property {string} DPI - the WMS GetMap dpi parameter
 * @property {string} TILED - the WMS GetMap tiled parameter
 */
export const StaticWmsGetMapParameters = createEnum({
    'FORMAT': 'format',
    'DPI': 'dpi',
    'TILED': 'tiled',
});

/**
 * List of static WMS GetMap parameters
 * @name StaticWmsGetMapParamList
 * @constant {Array<string>}
 */
export const StaticWmsGetMapParamList = deepFreeze([
    StaticWmsGetMapParameters.FORMAT,
    StaticWmsGetMapParameters.DPI,
    StaticWmsGetMapParameters.TILED,
]);

/**
 * @class
 * @name WMS
 */
export class WMS {

    constructor() {
        this._defaultGetFeatureInfoParameters = {
            repository: globalThis['lizUrls'].params.repository,
            project: globalThis['lizUrls'].params.project,
            SERVICE: 'WMS',
            REQUEST: 'GetFeatureInfo',
            VERSION: '1.3.0',
            CRS: 'EPSG:4326',
            INFO_FORMAT: 'text/html'
        };

        this._defaultGetLegendGraphicParameters = {
            repository: globalThis['lizUrls'].params.repository,
            project: globalThis['lizUrls'].params.project,
            SERVICE: 'WMS',
            REQUEST: 'GetLegendGraphic',
            VERSION: '1.3.0',
            FORMAT: 'application/json',
        };

        this._defaultGetStylesParameters = {
            repository: globalThis['lizUrls'].params.repository,
            project: globalThis['lizUrls'].params.project,
            SERVICE: 'WMS',
            REQUEST: 'GetStyles',
            VERSION: '1.1.1',
        };
    }

    /**
     * Get feature info from WMS
     * @param {object} options - optional parameters which can override this._defaultGetFeatureInfoParameters
     * @returns {Promise} Promise object represents data
     * @memberof WMS
     */
    async getFeatureInfo(options) {
        return Utils.fetchHTML(globalThis['lizUrls'].wms, {
            method: "POST",
            body: new URLSearchParams({
                ...this._defaultGetFeatureInfoParameters,
                ...options
            })
        });
    }

    /**
     * Get legend graphic from WMS
     * @param {object} options - optional parameters which can override this._defaultGetLegendGraphicsParameters
     * @returns {Promise} Promise object represents data
     * @throws {HttpError} In case of not successful response (status not in the range 200 – 299)
     * @throws {NetworkError} In case of catch exceptions
     * @memberof WMS
     */
    async getLegendGraphic(options) {
        const layers = options['LAYERS'] ?? options['LAYER'];
        // Check if layer is specified
        if (!layers) {
            return Promise.reject(
                new RequestError(
                    'LAYERS or LAYER parameter is required for getLegendGraphic request',
                    options,
                )
            );
        }
        const params = new URLSearchParams({
            ...this._defaultGetLegendGraphicParameters,
            ...options
        });
        // Check if multiple layers are specified
        if ((Array.isArray(layers) && layers.length == 1) ||
            (!Array.isArray(layers) && layers.split(',').length == 1)) {
            // Use GET request for single layer
            return Utils.fetchJSON(`${globalThis['lizUrls'].wms}?${params}`);
        }
        // Use POST request for multiple layers
        return Utils.fetchJSON(globalThis['lizUrls'].wms, {
            method: "POST",
            body: params,
        });
    }

    /**
     * Get legend graphic as PNG image URL from WMS
     * @param {object} options - optional parameters which can override this._defaultGetLegendGraphicsParameters
     * @returns {string} PNG image URL
     * @memberof WMS
     */
    getLegendGraphicPNG(options) {
        const layers = options['LAYERS'] ?? options['LAYER'];
        // Check if layer is specified
        if (!layers) {
            throw new RequestError(
                'LAYERS or LAYER parameter is required for getLegendGraphic request',
                options,
            );
        }

        const params = new URLSearchParams({
            ...this._defaultGetLegendGraphicParameters,
            ...options,
            FORMAT: 'image/png' // Force PNG format for external WMS layers
        });

        return `${globalThis['lizUrls'].wms}?${params}`;
    }

    /**
     * Get styles from WMS
     * @param {object} options - optional parameters which can override this._defaultGetStylesParameters
     * @returns {Promise} Promise object represents data
     * @memberof WMS
     */
    async getStyles(options) {
        return Utils.fetchXML(globalThis['lizUrls'].wms, {
            method: "POST",
            body: new URLSearchParams({
                ...this._defaultGetStylesParameters,
                ...options
            })
        });
    }
}