var __decorate=this&&this.__decorate||function(e,t,o,r){var a,n=arguments.length,s=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,o):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,r);else for(var i=e.length-1;i>=0;i--)(a=e[i])&&(s=(n<3?a(s):n>3?a(t,o,s):a(t,o))||s);return n>3&&s&&Object.defineProperty(t,o,s),s};import e from"@openremote/core";import{FlattenedNodesObserver as t}from"@polymer/polymer/lib/utils/flattened-nodes-observer.js";import{html as o,LitElement as r}from"lit";import{customElement as a,property as n,query as s}from"lit/decorators.js";import{LngLat as i,GeolocateControl as l}from"maplibre-gl";import{MapWidget as p}from"./mapwidget";import{style as d}from"./style";import"./markers/or-map-marker";import"./markers/or-map-marker-asset";import{OrMapMarker as m,OrMapMarkerChangedEvent as c}from"./markers/or-map-marker";import*as h from"./util";import{InputType as u,OrMwcInput as v}from"@openremote/or-mwc-components/or-mwc-input";import{OrMwcDialog as g,showDialog as y}from"@openremote/or-mwc-components/or-mwc-dialog";import{getMarkerIconAndColorFromAssetType as f}from"./util";import{i18next as C}from"@openremote/or-translate";import{debounce as _}from"lodash";export*from"./markers/or-map-marker";export*from"./markers/or-map-marker-asset";export*from"./or-map-asset-card";export class OrMapLoadedEvent extends CustomEvent{constructor(){super(OrMapLoadedEvent.NAME,{bubbles:!0,composed:!0})}}OrMapLoadedEvent.NAME="or-map-loaded";export class OrMapClickedEvent extends CustomEvent{constructor(e,t=!1){super(OrMapClickedEvent.NAME,{detail:{doubleClick:t,lngLat:e},bubbles:!0,composed:!0})}}OrMapClickedEvent.NAME="or-map-clicked";export class OrMapLongPressEvent extends CustomEvent{constructor(e){super(OrMapLongPressEvent.NAME,{detail:{doubleClick:!1,lngLat:e},bubbles:!0,composed:!0})}}OrMapLongPressEvent.NAME="or-map-long-press";export class OrMapGeocoderChangeEvent extends CustomEvent{constructor(e){super(OrMapGeocoderChangeEvent.NAME,{detail:{geocode:e},bubbles:!0,composed:!0})}}OrMapGeocoderChangeEvent.NAME="or-map-geocoder-change";export class CenterControl{onAdd(e){this.map=e;let t=document.createElement("div");t.classList.add("maplibregl-ctrl"),t.classList.add("maplibregl-ctrl-group");let o=document.createElement("button");o.className="maplibregl-ctrl-compass",o.addEventListener("click",t=>e.flyTo({center:this.pos,zoom:e.getZoom()}));let r=document.createElement("span");return r.className="maplibregl-ctrl-icon",o.appendChild(r),t.appendChild(o),this.elem=t,t}onRemove(e){this.map=void 0,this.elem=void 0}}let CoordinatesRegexPattern="^[ ]*(?:Lat: )?(-?\\d+\\.?\\d*)[, ]+(?:Lng: )?(-?\\d+\\.?\\d*)[ ]*$";function getCoordinatesInputKeyHandler(e){return t=>{if("Enter"===t.code||"NumpadEnter"===t.code){let o=t.target.value,r=o?{}:void 0;if(o){let e=o.split(/[ ,]/).filter(e=>!!e);2===e.length&&(r=new i(Number.parseFloat(e[0]),Number.parseFloat(e[1])))}e(r)}}}export class CoordinatesControl{constructor(e=!1,t){this._readonly=!1,this._readonly=e,this._valueChangedHandler=t}onAdd(e){this.map=e;let t=document.createElement("div");t.classList.add("maplibregl-ctrl"),t.classList.add("maplibregl-ctrl-group");let o=new v;return o.type=u.TEXT,o.outlined=!0,o.compact=!0,o.readonly=this._readonly,o.icon="crosshairs-gps",o.value=this._value,o.pattern=CoordinatesRegexPattern,o.onkeyup=getCoordinatesInputKeyHandler(this._valueChangedHandler),t.appendChild(o),this.elem=t,this.input=o,t}onRemove(e){this.map=void 0,this.elem=void 0}set readonly(e){this._readonly=e,this.input&&(this.input.readonly=e)}set value(e){this._value=e,this.input&&(this.input.value=e)}}export const geoJsonPointInputTemplateProvider=(e,t,r,a,n,s)=>{let p,d=!!(s&&s.disabled),m=!!(s&&s.readonly),c=!!(s&&s.compact),v=!!(s&&s.comfortable),_=new CenterControl,b=e=>{n&&(void 0!==e?n({value:e?h.getGeoJSONPoint(e):null}):n(void 0))},A=new CoordinatesControl(d,b);return{templateFunction:(t,r,a,n,s,M)=>{let k,w;t&&(k=(p=h.getLngLat(t))?Object.values(p):void 0);let E=k?k.join(", "):void 0;_.pos=p||void 0,A.readonly=d||m||n||a,A.value=E;let O=f(e),x=e=>{if(!m&&!d)if(p=e?h.getLngLat(e):null,w){let e=w.shadowRoot.getElementById("geo-json-point-marker");e.lng=p?p.lng:void 0,e.lat=p?p.lat:void 0,A.value=(k=p?Object.values(p):void 0)?k.join(", "):void 0}else b(p)},z=[[_,"bottom-left"],[A,"top-right"]];if(!m){let e=new l({positionOptions:{enableHighAccuracy:!0},showAccuracyCircle:!1,showUserLocation:!1});e.on("geolocate",e=>{x(new i(e.coords.longitude,e.coords.latitude))}),e.on("outofmaxbounds",e=>{x(new i(e.coords.longitude,e.coords.latitude))}),z.push([e,"bottom-left"])}let N=o`
            <or-map id="geo-json-point-map" class="or-map" @or-map-long-press="${e=>{x(e.detail.lngLat)}}" .center="${k}" .controls="${z}" .showGeoCodingControl=${!m}>
                <or-map-marker id="geo-json-point-marker" active .lng="${p?p.lng:void 0}" .lat="${p?p.lat:void 0}" .icon="${O?O.icon:void 0}" .activeColor="${O?"#"+O.color:void 0}" .colour="${O?"#"+O.color:void 0}"></or-map-marker>
            </or-map>
            <span class="long-press-msg">${C.t("longPressSetLoc")}</span>
        `;if(c){let e=N;N=o`
                <style>
                    #geo-json-point-input-compact-wrapper {
                        display: table-cell;
                    }
                    #geo-json-point-input-compact-wrapper > * {
                        vertical-align: middle;
                    }
                </style>
                <div id="geo-json-point-input-compact-wrapper">
                    <or-mwc-input style="width: auto;" .comfortable="${v}" .type="${u.TEXT}" .value="${E}" .pattern="${CoordinatesRegexPattern}" @keyup="${e=>getCoordinatesInputKeyHandler(b)(e)}"></or-mwc-input>
                    <or-mwc-input style="width: auto;" .type="${u.BUTTON}" compact icon="crosshairs-gps" @or-mwc-input-changed="${()=>{w=y(new g().setContent(e).setStyles(o`
                            <style>
                                .dialog-container {
                                    flex-direction: column !important;
                                }
                                .dialog-container .long-press-msg {
                                    display: block;
                                    text-align: center;
                                }
                                or-map {
                                    width: 600px !important;
                                    min-height: 600px !important;
                                }
                            </style>
                        `).setActions([{actionName:"none",content:"none",action:()=>{x(null),b(p)}},{actionName:"ok",content:"ok",action:()=>{b(p)}},{default:!0,actionName:"cancel",content:"cancel"}]))}}"></or-mwc-input>
                </div>
            `}return N},supportsHelperText:!1,supportsLabel:!1,supportsSendButton:!1,validator:()=>!p||void 0!==p.lat&&null!==p.lat&&void 0!==p.lng&&null!==p.lng}};let OrMap=class extends r{constructor(){super(),this.type=e.mapType,this._markerStyles=[],this.showGeoCodingControl=!1,this.showBoundaryBoxControl=!1,this.useZoomControl=!0,this.showGeoJson=!0,this.boundary=[],this._loaded=!1,this._markers=[],this.addEventListener(c.NAME,this._onMarkerChangedEvent)}firstUpdated(t){super.firstUpdated(t),e.ready&&this.loadMap()}get markers(){return this._markers}connectedCallback(){super.connectedCallback()}disconnectedCallback(){var e;super.disconnectedCallback(),this._observer&&this._observer.disconnect(),this._resizeObserver&&this._resizeObserver.disconnect(),null==(e=this._map)||e.unload()}render(){return o`
            <div id="container">
                <div id="map"></div>
                <slot></slot>
                <a id="openremote" href="https://openremote.io/" target="_blank">
                    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAABGdBTUEAAYagMeiWXwAAAAJiS0dEAP+Hj8y/AAAESUlEQVRIx5XVbWzdZRnH8c//f07POe36sK7SrYXZjYGzbBokOqd4QtKATdnMDFFSkoFzmWGRQOAFSoYnsBSzxBdmGsN4Y7LEFwZkUdHpDoja/AnJjBvp1sm2upW5PtAV+zBS+7Tz//tiLe0emPF+d9/39fvmunJf9+8K3HBF1drFzurVn5+5XkTwPwBNOt1s0pCjDnnT+Xzy/wOa5jaXnLLfLwzlF0WENwaYckyvUTHS1tnjl+6JFqk+JoMOqqy2JqjPVpXP1k7U1+Ty8paBPk97NX/pYwEdgZUetNkdlirDrHGnyv6y5r3lm4M2WVzwpJfz8XUBHTntnrJO6qqLWE9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QI1P+YxaGcwY1+20kasnM/wXCa5/Ik1hKTEAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTktMDgtMjBUMTU6MTc6NTUrMDA6MDCwJSdSAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE5LTA4LTIwVDE1OjE3OjU1KzAwOjAwwXif7gAAAABJRU5ErkJggg==" />
                </a>
            </div>
        `}updated(e){var t;super.updated(e),(e.has("center")||e.has("zoom"))&&this.flyTo(this.center,this.zoom),e.has("boundary")&&this.showBoundaryBoxControl&&(null==(t=this._map)||t.createBoundaryBox(this.boundary))}refresh(){this._map&&this._map.loadViewSettings().then(()=>{this._map&&(this._map.setCenter(),this._map.flyTo())})}loadMap(){this._loaded||(this._mapContainer&&this._slotElement&&(this._map=new p(this.type,this.shadowRoot,this._mapContainer,this.showGeoCodingControl,this.showBoundaryBoxControl,this.useZoomControl,this.showGeoJson).setCenter(this.center).setZoom(this.zoom).setControls(this.controls).setGeoJson(this.geoJson),this._map.load().then(()=>{this._observer=new t(this._slotElement,e=>{this._processNewMarkers(e.addedNodes),this._processRemovedMarkers(e.removedNodes)}),null==(e=this._resizeObserver)||e.disconnect(),this._resizeObserver=new ResizeObserver(_(()=>{this.resize()},200));var e,o,r=null==(o=this._mapContainer)?void 0:o.parentElement;r&&this._resizeObserver.observe(r)})),this._loaded=!0)}resize(){this._map&&this._map.resize()}flyTo(e,t){this._map&&this._map.flyTo(e,t)}_onMarkerChangedEvent(e){this._map&&this._map.onMarkerChanged(e.detail.marker,e.detail.property)}_processNewMarkers(e){e.forEach(e=>{if(this._map&&e instanceof m){this._markers.push(e);let t=e.constructor.name;if(0>this._markerStyles.indexOf(t)){let o=e.constructor.styles,r=[];o&&(Array.isArray(o)?r=o:r.push(o),r.forEach(e=>{let t=document.createElement("style");t.textContent=String(e.toString()),this._mapContainer.children.length>0?this._mapContainer.insertBefore(t,this._mapContainer.children[0]):this._mapContainer.appendChild(t)})),this._markerStyles.push(t)}this._map.addMarker(e)}})}_processRemovedMarkers(e){e.forEach(e=>{if(this._map&&e instanceof m){let t=this._markers.indexOf(e);t>=0&&this._markers.splice(t,1),this._map.removeMarker(e)}})}};OrMap.styles=d,__decorate([n({type:String})],OrMap.prototype,"type",void 0),__decorate([n({type:String,converter:{fromAttribute(e,t){if(!e)return;let o=e.split(",");if(2===o.length)return new i(Number(o[0]),Number(o[1]))},toAttribute(e,t){let o=h.getLngLat(e);return o?""+o.lng+","+o.lat:""}}})],OrMap.prototype,"center",void 0),__decorate([n({type:Number})],OrMap.prototype,"zoom",void 0),__decorate([n({type:Boolean})],OrMap.prototype,"showGeoCodingControl",void 0),__decorate([n({type:Boolean})],OrMap.prototype,"showBoundaryBoxControl",void 0),__decorate([n({type:Boolean})],OrMap.prototype,"useZoomControl",void 0),__decorate([n({type:Object})],OrMap.prototype,"geoJson",void 0),__decorate([n({type:Boolean})],OrMap.prototype,"showGeoJson",void 0),__decorate([n({type:Array})],OrMap.prototype,"boundary",void 0),__decorate([s("#map")],OrMap.prototype,"_mapContainer",void 0),__decorate([s("slot")],OrMap.prototype,"_slotElement",void 0),OrMap=__decorate([a("or-map")],OrMap);export{h as Util,OrMap};