var customBaseLayerPath = new URL(document.currentScript.src)
var getScriptUrl = () => {
    return customBaseLayerPath
}
var customBaseLayer = () => {
    var createEvent = (name, data = {}) => {
        var event = new CustomEvent(name, { detail: data });
        window.parent.document.dispatchEvent(event);
    };
    var makeEventListener = (name, callback) => {
        window.parent.document.addEventListener(name, callback, false)
    }
    var getProxyServiceURL = (url, serviceType) => {
        if (!url.startsWith('http')) alert('Brak protokołu http w podanym URL do usługi WMS/WMTS.')
        return `${window.location.protocol}//${window.location.hostname}/GetServiceCapabilities.php?url=${url}&service=${serviceType}`
    }
    var onBaselayerChanged = () => {
        $('#switcher-baselayer-select')
            .change((e) => {
                createEvent('OL_CHANGE_VISIBLE_LAYER', { layerName: $('option:selected', $(e.currentTarget)).text() })
            })
    }
    var createBaseLayer = (data) => {
        var onLayerCreated = () => {
            $('#switcher-baselayer-select')
                .append($('<option>', { value: 'ol650' })
                    .text(data.layerName)
                )
            $('#switcher-baselayer').css('display', 'block')
            $('#message p:contains("Dodano warstę bazową:")').parent().remove()
            if ($('#switcher-baselayer-select option').length === 1) {
                // createEvent('OL_CHANGE_VISIBLE_LAYER', { layerName: layerName })
                $('#switcher-baselayer-select').find(`option[text="${data.layerName}"]`).attr('selected', 'selected')
                $('#switcher-baselayer-select').change()
            }
        }
        data.url = getProxyServiceURL(data.url, data.service)
        createEvent('OL_ADD_NEW_LAYER', { ...data, callback: onLayerCreated });
    }
    var getParamsUrl = (fileName = 'params.json') => {
        var sUrl = getScriptUrl()
        var sParams = new URLSearchParams(sUrl.search)
        var sPath = sParams.get('path')
        sUrl.searchParams.set('path', sPath.replace('customBaseLayer.js', fileName))
        return sUrl
    }
    var readConfigJSON = () => {
        var onSuccess = (data) => { data.baseLayers.forEach((layer) => { createBaseLayer(layer) }) }
        $.getJSON(getParamsUrl(), onSuccess)
            .error(e => { console.error('Nie powiodło się pobieranie pliku konfiguracyjnego'); })
    }
    var onMapCreated = () => {
        onBaselayerChanged()
        readConfigJSON()
    }
    lizMap.events.on({
        uicreated: function (e) {
            makeEventListener('OL_MAP_CREATED', onMapCreated)
        }
    });
};
customBaseLayer();