(()=>{var qe=Object.defineProperty,Oe=Object.defineProperties;var Ce=Object.getOwnPropertyDescriptors;var X=Object.getOwnPropertySymbols;var ke=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var Z=(a,e,t)=>e in a?qe(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,b=(a,e)=>{for(var t in e||(e={}))ke.call(e,t)&&Z(a,t,e[t]);if(X)for(var t of X(e))Re.call(e,t)&&Z(a,t,e[t]);return a},ee=(a,e)=>Oe(a,Ce(e));var te=(a,e,t)=>new Promise((n,s)=>{var r=c=>{try{i(t.next(c))}catch(l){s(l)}},o=c=>{try{i(t.throw(c))}catch(l){s(l)}},i=c=>c.done?n(c.value):Promise.resolve(c.value).then(r,o);i((t=t.apply(a,e)).next())});var S,$,ae;function Ie(){S.dataset.navState="displayed",S.classList.remove("state-off"),S.classList.add("state-on"),$.classList.add("a-show")}function x(){S.dataset.navState="hidden",S.classList.remove("state-on"),S.classList.add("state-off"),$.classList.add("a-hide"),$.classList.remove("a-show"),setTimeout(()=>{$.classList.remove("a-hide")},300)}function ne(){console.log("HUD init"),S=document.querySelector(".hud .nav-toggle"),$=document.querySelector(".hud .navigation"),ae=document.querySelector(".hud .reload-screen"),S.addEventListener("click",a=>{a.currentTarget.dataset.navState!="displayed"?Ie():x()}),ae.addEventListener("click",a=>{Screens.reload()})}var A=class{constructor(e,t,n){this.screens={},this.routesMap={},this.currentScreen=null,this.eventsHandlers={switch:[],reload:[],reinit:[],errorScreen:[]},this.screensContainer=document.querySelector(e),this.loader=document.querySelector(t),this.errorScreen=document.querySelector(n),console.log("Screens Init")}add(e,t){if(typeof t!="object")return console.error("Screens: screens must be object");if(typeof(t==null?void 0:t.alias)=="undefined")return console.error("Screens: undefined alias");if(typeof(t==null?void 0:t.renderer)!="function")return console.error("Screens: renderer must be function");this.screens[t.alias]=b({route:e},t),this.routesMap[e]=t.alias}switch(e){var n;if(this.runSwitchHandlers(e),this.hideErrorScreen(),this.showLoader(),(n=this.currentScreen)==null||n.DOMObject.remove(),typeof this.screens[e]=="undefined"){console.error(`Screens: "${e}" not found`);return}this.currentScreen=this.screens[e];let t=document.createElement("div");t.classList.add("screen"),t.id=e,t.dataset.alias=e,t.innerHTML=this.currentScreen.renderer(),this.currentScreen.DOMObject=t,this.screensContainer.append(this.currentScreen.DOMObject),this.currentScreen.initer(this)}reload(){this.currentScreen&&(this.runReloadHandlers(this.currentScreen.alias),this.switch(this.currentScreen.alias))}reinit(){this.currentScreen&&(this.currentScreen.initer(this),this.runReinitHandlers())}routing(){setInterval(()=>{let e=document.location.hash.split("#!")[1];if(typeof e=="undefined"||e=="")return;let t=typeof this.routesMap[e]=="undefined"?"not-found-screen":this.routesMap[e];(!this.currentScreen||this.currentScreen.alias!=t)&&this.switch(t)},50)}ready(){this.currentScreen!=null&&(this.currentScreen.DOMObject||(this.currentScreen.DOMObject=document.getElementsById(this.currentScreen.alias)),this.hideLoader(),this.currentScreen.DOMObject.classList.add("a-show"))}error(e,t){var n;(n=this.currentScreen)==null||n.DOMObject.remove(),this.errorScreen.querySelector(".error-title").innerHTML=e,this.errorScreen.querySelector(".error-text").innerHTML=t,this.showErrorScreen(),this.runErrorScreenHandlers()}hideLoader(){this.loader.classList.remove("a-show")}showLoader(){this.loader.classList.add("a-show")}showErrorScreen(){this.errorScreen.classList.add("a-show")}hideErrorScreen(){this.errorScreen.classList.remove("a-show")}getScreens(){return this.screens}getRoutesMap(){return this.routesMap}onSwitch(e){this.eventsHandlers.switch.push(e)}onReaload(e){this.eventsHandlers.reload.push(e)}onReinit(e){this.eventsHandlers.reinit.push(e)}onErrorScreen(e){this.eventsHandlers.errorScreen.push(e)}runSwitchHandlers(e){let t=Object.keys(this.routesMap).filter(n=>this.routesMap[n]==e);for(let n of this.eventsHandlers.switch)n(this,e,t.length?t[0]:void 0)}runReloadHandlers(e){for(let t of this.eventsHandlers.reload)t(this,e)}runReinitHandlers(){for(let e of this.eventsHandlers.reinit)e(this)}runErrorScreenHandlers(){for(let e of this.eventsHandlers.errorScreen)e(this)}};function xe(a,e,t,n){return`
		<div class="toast toast-${a}" role="alert">
	    <div class="toast-content">
	      <h4 class="toast-title">${e} ${t}</h4>
	      <p class="toast-text">${n}</p>
	    </div>
	    <button class="btn-icon toast-close" type="button" aria-label="Close">\u2715</button>
	  </div>
	`}function Ne(a,e){if(e!=null&&e.alone&&document.querySelectorAll(".toast").forEach(t=>t.close()),a.close=function(){this.classList.add("a-hide"),setTimeout(()=>{this.remove()},300)},a.querySelector(".toast-close").addEventListener("click",t=>{a.close()}),a.show=function(){document.querySelector("body").append(a),setTimeout(()=>{a.classList.add("a-show")},10)},Screens.onSwitch((t,n)=>{setTimeout(()=>{a==null||a.close()},1e4)}),a.addEventListener("mouseover",t=>a.ishovered=!0),a.addEventListener("mouseout",t=>a.ishovered=!1),e!=null&&e.lifetime){console.log(e);let t=setInterval(()=>{a.ishovered||(a.close(),clearInterval(t))},e==null?void 0:e.lifetime)}return a}function T(a,e,t,n,s){let r=document.createElement("div");return r.innerHTML=xe(a,e,t,n),Ne(r.childNodes[1],s)}function je(a,e,t){return typeof t=="undefined"&&(t={}),typeof t.lifetime=="undefined"&&(t.lifetime=4e3),typeof t.alone=="undefined"&&(t.alone=!0),T("success",'<i class="ph ph-check-circle"></i>',a,e,t)}function Pe(a,e,t){return T("info",'<i class="ph ph-info"></i>',a,e,t)}function Ue(a,e,t){return T("warning",'<i class="ph ph-warning"></i>',a,e,t)}function se(a,e,t){return T("danger",'<i class="ph ph-warning-octagon"></i>',a,e,t)}var re={create:T,createInfo:Pe,createSuccess:je,createWarning:Ue,createError:se,createDanger:se};function Fe(a){let e="";for(let t of a){let n="",s="";t.route&&(n=`<a class="list-action" href="${t.route}">`,s="</a>"),e+=`
			<li class="list-item ${t.is_active?"list-item-active":""}">
				${n}${t.content}${s}
			</li>
		`}return`
		<div class="sidebar block">
			<ul class="list list-nav">
				${e} 
			</ul>
		</div>
	`}function Be(a,e,t,n){let s='<tr class="table-row">',r=0;for(let p in e)s+=`<th scope="col">${e[p]}</th>`,r++;s+="</tr>";let o="";for(let p of t){o+='<tr class="table-row">';for(let m in e)o+=`<td>${p[m]}</td>`;o+="</tr>"}let i="";typeof n!="undefined"&&(i=`
			<tfoot class="table-foot">
				<tr class="table-row">
					<td colspan="${r}">
						${n}
					</td>
				</tr>
			</tfoot>
		`);let c=a?`<caption class="table-caption">${a}</caption>`:"",l=t.length?`<thead class="table-head">${s}</thead>`:"";return o=t.length?o:'<tr><td class="is-empty">Empty</td></tr>',`
		<table class="table devices-lists ${t.length?"":"table-empty"}">
			${c}
			${l}
			<tbody class="table-body">${o}</tbody>
			${i}
		</table>
	`}function ie(a,e,t){let n=document.createElement(a);for(let[s,r]of Object.entries(e))s==="class"?n.className=r:s==="dataset"?Object.assign(n.dataset,r):n.setAttribute(s,r);return n.innerHTML=typeof t!="undefined"?t:"",n}function ze(a,e){return["primary","success","secondary","info","warning","error","danger"].indexOf(a)<0?console.error("createAlert()","Error of type: "+a):ie("div",{class:`alert alert-${a}`},e)}function Je(a){let e={device_name:"name",device_hard_id:"device_id",device_ip:"ip",device_type:"type",ip_address:"ip",mac_address:"mac",device_mac:"mac",core_version:"firmware_core_version"},t={};for(let n in a){if(typeof e[n]!="undefined"){t[e[n]]=a[n];continue}t[n]=a[n]}return t}function Ve(a,e){if((a==null?void 0:a.isLoading)==e)return!1;if(e)a.isLoading=!0,a.originalContent=a.innerHTML,a.classList.contains("with-icon")?a.originalWithIcon=!0:a.classList.add("with-icon"),a.classList.add("loading-state"),a.setAttribute("disabled","disabled"),a.innerHTML='<i class="ph-bold ph-spinner"></i> Loading';else{if(a.isLoading=!1,!a.originalContent)return!1;a.removeAttribute("disabled"),a.classList.remove("loading-state"),a.originalWithIcon||a.classList.remove("with-icon"),a.innerHTML=a.originalContent}return a}function We(a,e){if((a==null?void 0:a.isLoading)==e)return!1;let t=a.querySelector(".device-icon");if(e)a.isLoading=!0,a.originalContent=t.innerHTML,a.classList.add("loading-state"),a.setAttribute("disabled","disabled"),t.innerHTML='<i class="ph-bold ph-spinner"></i>';else{if(a.isLoading=!1,!a.originalContent)return!1;a.removeAttribute("disabled"),a.classList.remove("loading-state"),t.innerHTML=a.originalContent}return a}function Ye(a,e){return e=e!=null?e:"",`
		<div class="container">
			<div class="row g-6">
				<div class="col sidebar-container">
					${a}
				</div>
				<div class="col main-container w-100">
					${e}
				</div>
			</div>
		</div>
	`}function Ge(a){return a=="active"?'<span class="badge badge-success">Online</span>':'<span class="badge badge-warning">Offline</span>'}function Ke(a){return a=="enabled"?'<span class="badge badge-success">Enabled</span>':'<span class="badge badge-primary">Disabled</span>'}function Qe(a){let e=new Date(a.replace(" ","T")),n=Math.floor((new Date-e)/1e3);if(n<60)return"less than a minute ago";let s=Math.floor(n/60),r=Math.floor(s/60),o=Math.floor(r/24);if(s<60)return`${s} minute${s!==1?"s":""} ago`;if(r<24){let i=s%60;return`${r} hour${r!==1?"s":""} ${i} minute${i!==1?"s":""} ago`}return`${o} day${o!==1?"s":""} ago`}function Xe(a){let e=new Date(a.replace(" ","T")),t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=new Date(e.getFullYear(),e.getMonth(),e.getDate()),r=Math.floor((n-s)/864e5),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");if(r===0)return`Today at ${o}:${i}`;if(r===1)return`Yesterday at ${o}:${i}`;let c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return`${e.getDate()} ${c[e.getMonth()]} ${e.getFullYear()} at ${o}:${i}`}function Ze(){return`
		<div class="circle-loader">
			<i class="ph-bold ph-spinner normalize"></i>
			Loading
		</div>
	`}function et(){return`
		<div class="empty-here">
			<div class="icon"><i class="ph ph-placeholder normalize"></i></div>
			<p class="text-msg">It's empty here yet</p>
		</div>
	`}var oe={template:{sidebarNav:Fe,table:Be,createElement:ie,createAlert:ze,mainTemplate:Ye,connectionStatusBadge:Ge,toogleStateBadge:Ke,circleLoaderHTML:Ze,emptyHereHTML:et},unification:{deviceFieldsUnification:Je,timeAgo:Qe,formatDate:Xe},states:{btnLoadingState:Ve,cardScriptActionLoadingState:We}};var M=class{constructor(e){this.core=e}actions_list(e){return this.core.api_get("/api/v1/scripts/actions/list",e)}scopes_list(e){return this.core.api_get("/api/v1/scripts/scopes/list",e)}regular_list(e){return this.core.api_get("/api/v1/scripts/regular/list",e)}scope_get_by_filename(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/scopes/name/${n}`,t,{})}scope_create(e,t){return this.core.api_post("/api/v1/scripts/scopes/new",e,t)}scope_update(e,t){return this.core.api_post("/api/v1/scripts/scopes/update",e,t)}action_enable(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/actions/alias/${n}/enable`,t)}action_disable(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/actions/alias/${n}/disable`,t)}regular_enable(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/regular/alias/${n}/enable`,t)}regular_disable(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/regular/alias/${n}/disable`,t)}scope_enable(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/scopes/name/${n}/enable`,t)}scope_disable(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/scopes/name/${n}/disable`,t)}scope_remove(e,t){let n=encodeURIComponent(String(e||""));return this.core.api_get(`/api/v1/scripts/scopes/name/${n}/remove`,t)}run(e,t){return this.core.api_post("/api/v1/scripts/actions/run",e,t)}place_in_area(e,t){return this.core.api_post("/api/v1/scripts/place-in-area",e,t)}unassign_from_area(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/scripts/id/${n}/unassign-from-area`,t)}};var D=class{constructor(e){this.core=e}list(e){return this.core.api_get("/api/v1/devices/list",e)}scanning_setup(e){return this.core.api_get("/api/v1/devices/scanning/setup",e)}scanning_all(e){return this.core.api_get("/api/v1/devices/scanning/all",e)}setup_new_device(e,t){return this.core.api_post("/api/v1/devices/setup/new-device",e,t)}info(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/devices/id/${n}/info`,t)}get(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/devices/id/${n}`,t)}status(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/devices/id/${n}/status`,t)}action(e,t){return this.core.api_post("/api/v1/devices/action",e,t)}remove(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/devices/id/${n}/remove`,t)}reboot(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/devices/id/${n}/reboot`,t)}place_in_area(e,t){return this.core.api_post("/api/v1/devices/place-in-area",e,t)}unassign_from_area(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/devices/id/${n}/unassign-from-area`,t)}};var q=class{constructor(e){this.core=e}list(e){return this.core.api_get("/api/v1/areas/list",e)}inner_list(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/areas/id/${n}/list`,t)}new_area(e,t){return this.core.api_post("/api/v1/areas/new-area",e,t)}remove(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/areas/id/${n}/remove`,t)}place_in_area(e,t){return this.core.api_post("/api/v1/areas/place-in-area",e,t)}update_display_name(e,t){return this.core.api_post("/api/v1/areas/update-display-name",e,t)}update_alias(e,t){return this.core.api_post("/api/v1/areas/update-alias",e,t)}devices(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/areas/id/${n}/devices`,t)}scripts(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/areas/id/${n}/scripts`,t)}unassign_from_area(e,t){let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/areas/id/${n}/unassign-from-area`,t)}types_list(e){return this.core.api_get("/api/v1/areas/types/list",e)}reboot_devices(e,t){if(e==null)return this.core.api_get("/api/v1/areas/reboot_devices",t);let n=encodeURIComponent(String(e));return this.core.api_get(`/api/v1/areas/id/${n}/reboot_devices`,t)}};function ce(a){if(!a||typeof a!="object")return"";let e=new URLSearchParams;Object.entries(a).forEach(([n,s])=>{s!=null&&e.append(n,String(s))});let t=e.toString();return t?`?${t}`:""}function tt(a,e){let t=String(a||"").replace(/\/+$/,""),n=String(e||"").replace(/^\/+/,"");return`${t}/${n}`}function at(a){try{return{ok:!0,data:JSON.parse(a)}}catch(e){return{ok:!1,error:e}}}var O=class{constructor(e){this.base_url=(e==null?void 0:e.base_url)||"",this.token=(e==null?void 0:e.token)||"",this.timeout_ms=Number.isFinite(e==null?void 0:e.timeout_ms)?e.timeout_ms:15e3,this.default_headers=(e==null?void 0:e.default_headers)||{},this.on_unauthorized=typeof(e==null?void 0:e.on_unauthorized)=="function"?e.on_unauthorized:null,this.proxy_path=(e==null?void 0:e.proxy_path)||"",this.scripts=new M(this),this.devices=new D(this),this.areas=new q(this)}set_base_url(e){this.base_url=e||""}set_token(e){this.token=e||""}set_proxy_path(e){this.proxy_path=e||""}_wrap_path(e,t){if(!this.proxy_path)return t?`${e}${ce(t)}`:e;let n=b({path:e},t||{});return`${this.proxy_path}${ce(n)}`}request(e,t,n,s,r){let o=typeof s=="function"?s:()=>{},i=tt(this.base_url,t),c=new AbortController,l=Number.isFinite(r==null?void 0:r.timeout_ms)?r.timeout_ms:this.timeout_ms,d=setTimeout(()=>c.abort(),l),p=b(b({},this.default_headers),(r==null?void 0:r.headers)||{});this.token&&(p.Authorization=`Bearer ${this.token}`);let m;n!=null&&(p["Content-Type"]="application/json",m=JSON.stringify(n)),fetch(i,{method:e,headers:p,body:m,signal:c.signal}).then(u=>te(this,null,function*(){clearTimeout(d);let h={url:i,method:e,status_code:u.status,headers:u.headers},v=yield u.text(),I=at(v),g=I.ok?I.data:v;if(!u.ok){let E={type:"http_error",message:`HTTP ${u.status}`,status_code:u.status,raw:g};if((u.status===401||u.status===403)&&this.on_unauthorized)try{this.on_unauthorized({error:E,meta:h})}catch(Q){}return o(E,null,h)}if(I.ok&&g&&typeof g=="object"){let E=g.status;if(E===!1||E==="error"){let Q={type:"api_error",message:g.message||"API error",status_code:u.status,raw:g,field:g.field};return o(Q,null,h)}}return o(null,g,h)})).catch(u=>{clearTimeout(d);let v=u&&(u.name==="AbortError"||String(u).includes("AbortError"))?{type:"timeout",message:`Timeout after ${l}ms`}:{type:"network_error",message:(u==null?void 0:u.message)||"Network error",details:u};return o(v,null,{url:i,method:e,status_code:0,headers:null})})}get(e,t,n){return this.request("GET",e,null,t,n)}post(e,t,n,s){return this.request("POST",e,t,n,s)}api_get(e,t,n,s){return this.get(this._wrap_path(e,n),t,s)}api_post(e,t,n,s,r){return this.post(this._wrap_path(e,s),t,n,r)}};function C(a){return Helper.template.sidebarNav([{content:'<span class="list-label"><i class="ph ph-cpu"></i> Devices</span>',route:"/#!/devices",is_active:a=="devices"},{content:'<span class="list-label"><i class="ph ph-magnifying-glass"></i> Scanning</span>',route:"/#!/devices/scanning",is_active:a=="scanning"}])}function y(a,e,t){Helper.states.btnLoadingState(e,!0);let n=e.dataset.deviceId,s=e.dataset.deviceName,r=e.dataset.deviceAlias;a.devices.reboot(n,(o,i,c)=>{Helper.states.btnLoadingState(e,!1),console.log("Reboot done",o,i,c),t==null||t.close(),i?(setTimeout(()=>Screens.reinit(),8e3),Toasts.createSuccess("Reboot successful",`Device: ${s}<br>
					Alias: <b>${r}</b>`).show()):Toasts.createError("Reboot failed",`Device: ${s}<br>
					Alias: <b>${r}</b>`).show()})}var f,N,le,_,k,H,j={area:"areas",device:"devices",action:"scripts"};function P(){let a=f.querySelector(".current-area");for(let e of le)if(e.id==_)return a.innerHTML=`${e.display_name}`;a.innerHTML=`Area ID ${_}`,it()}function nt(a){k[j[H]].unassign_from_area(a,(e,t,n)=>{if(console.log(`sh_api[${j[H]}].unassign_from_area`,e,t,n),!t||t.data.status)return Toasts.createError("Error of unassigning",t?t.data.error_alias:"Error of request").show();_=0,P(),U(),Toasts.createSuccess("Successfully unassigning","Successfully unassigning").show(),Screens.reinit()})}function st(a,e){a[j[H]].place_in_area(e,(t,n,s)=>{if(console.log("sh_api.areas.place_in_area",t,n,s),!n||!n.status)return console.error("Component placeInArea",t,n,s);let r=f.querySelector(".current-area");Toasts.createSuccess("Successfully applied","Successfully applied").show(),_=e.place_in_area_id,P(),U(),Screens.reinit(),console.log("Success",n)})}function rt(a,e){k.areas.list((t,n,s)=>{if(console.log("sh_api.areas.list",t,n,s),!n)return console.error("sh_api.areas.list",t);le=n.data.areas,P();let r={};for(let i of n.data.areas)H=="area"&&i.id==a||(r[i.id]=i.display_name);let o=advancedSelect(f.querySelector(".select-area"),r,"Nothing found");f.querySelector(".advanced-select-container").append(o),o.advancedSelect.addEventListener("changed",i=>{e(i,n.data.areas)}),N.innerHTML="",N.append(f)})}function U(){let a=f.querySelector(".form-container");a.classList.remove("a-show"),a.classList.add("a-hide"),setTimeout(()=>a.classList.remove("a-hide"),300)}function it(){let a=f.querySelector(".remove-parent-id");_==0?a.classList.add("d-none"):a.classList.remove("d-none")}function w(a,e,t,n,s){k=a,N=e,_=s,H=t,f=document.createElement("div"),f.classList.add("component"),f.classList.add("place-in-area-component"),f.innerHTML=`
		<span class="current-area"></span>
		<button class="btn-icon without-hover remove-parent-id"><i class="ph ph-backspace"></i></button>
		<button class="btn btn-primary with-icon show-place-in-area">
			<i class="ph ph-map-pin-line"></i>
			Place In Area
		</button>
		<div class="block form-group form-container">
			<button class="btn-icon hide-place-in-area">
				<i class="ph ph-x"></i>
			</button>
			<label class="label">
				Select Area
				<i class="ph ph-magnifying-glass"></i>
				<input type="text" class="input select-area" placeholder="Search">
			</label>
			<div class="advanced-select-container"></div>
		</div>
	`,rt(n,(o,i)=>{let c=o.advancedSelect.value();if(!c.isOption)return;let l=Object.keys(c.option)[0];st(k,{target_id:n,place_in_area_id:l})});let r=f.querySelector(".form-container");f.querySelector("button.show-place-in-area").addEventListener("click",o=>{r.classList.contains("a-show")?(r.classList.remove("a-show"),r.classList.add("a-hide"),setTimeout(()=>r.classList.remove("a-hide"),300)):r.classList.add("a-show")}),f.querySelector("button.hide-place-in-area").addEventListener("click",o=>{U()}),f.querySelector("button.remove-parent-id").addEventListener("click",o=>{nt(n)})}var de={relay:(a,e)=>{let t="";for(let n of e.channels){let s=n.state=="off"?"OFF":"ON",r=n.state=="on"?"badge-success":"";t+=`
				<span class="badge ${r}">id${n.id}: <b>${s}</b></span>
			`}return`<div class="channels f-grid g-2">${t}</div>`},button:(a,e)=>{let t={enabled:"badge-success",disabled:"",mute:"badge-primary-outline",waiting:"badge-warning",error:"badge-error"},n="";for(let s of e.channels)n+=`
				<span class="badge ${t[s.indicator]}">id${s.id}: <b>${s.indicator}</b></span>
			`;return`<div class="channels f-grid g-2">${n}</div>`}};function ot(a,e,t){return typeof de[a]!="undefined"?de[a](e,t):"Unknown device type<br>"+JSON.stringify(t)}function F(a,e,t){let n=Helper.template.createElement("div",{class:"component device-status-component"},"");return n.innerHTML=Helper.template.circleLoaderHTML(),a.devices.status(e,(s,r,o)=>{if(console.log("sh_api.devices.status",s,r),!r)return n.innerHTML=`
				<span class="badge badge-error"><i class="ph ph-warning-octagon fs-lg normalize"></i> Loading Error</span>
			`,console.error("deviceStatusComponent",`DeviceID ${e}`);n.innerHTML=ot(t,r.data.device.alias,r.data.device.device_response)}),n}function ue(a,e){return console.log(a),Modals.create("device-popup",{title:`Device ${a.name}`,body:t=>{var o;let n={area_id:"place-in-area-component-container",ip:"device-ip",status:"status-container"},s=(i,c)=>{let l={ip:"<code>{{value}}</code>",state:d=>`<span class="badge ${{active:"badge-success",removed:"badge-error",freezed:"badge-warning"}[d]}">${d}</span>`,connection_state:d=>`<span class="badge ${d=="active"?"badge-success":"badge-warning"}">${d}</span>`,mac:"<code>{{value}}</code>",alias:'<i class="ph ph-link-simple-break normalize"></i> {{value}}',device_id:"<code>{{value}}</code>",last_contact:d=>Helper.unification.timeAgo(d),create_at:d=>Helper.unification.formatDate(d),update_at:d=>Helper.unification.formatDate(d)};return l[i]?typeof l[i]=="function"?l[i](c):l[i].replaceAll("{{value}}",c):c},r="";for(let i in a){let c=(o=n[i])!=null?o:"";r+=`
					<tr class="table-row">
						<th>${i}: </th>
						<td class="${c}">${s(i,a[i])}</td>
					</tr>
				`}return`
				<div class="block">
					<table class="table" style="border: 0">
						<tbody class="table-body">
							${r}
						</tbody>
					</table>
				</div>
			`},actions:t=>{let n=Helper.template.createElement("button",{class:"btn btn-primary"},"Close"),s=Helper.template.createElement("button",{class:"btn btn-warning with-icon"},'<i class="ph ph-arrow-clockwise"></i> Reboot'),r=Helper.template.createElement("button",{class:"btn btn-danger with-icon"},'<i class="ph ph-trash"></i> Remove');return n.addEventListener("click",o=>{t.close()}),s.dataset.deviceId=a.id,s.dataset.deviceName=a.name,s.dataset.deviceAlias=a.alias,s.addEventListener("click",o=>{s.getAttribute("disabled")||y(e,o.currentTarget,t)}),r.addEventListener("click",o=>{r.getAttribute("disabled")||(Helper.states.btnLoadingState(r,!0),confirmPopup("Are you sure you want to remove this device?",()=>{e.devices.remove(a.id,(i,c,l)=>{Helper.states.btnLoadingState(r,!1),console.log("Was removed"),t.close(),Screens.reinit(),setTimeout(()=>{Toasts.createSuccess("Removed",`
										Device: ${a.name}<br>
										Alias: <b>${a.alias}</b><br>
										IP: <b>${a.ip}</b>
										`).show()},300)})},()=>{Helper.states.btnLoadingState(r,!1),console.log("CANCELED")}))}),[n,s,r]},onready:t=>{w(e,t.querySelector(".place-in-area-component-container"),"device",a.id,a.area_id),t.querySelector(".status-container").append(F(e,a.id,a.type))}})}function ct(a){let e=[];for(let t of a.devices)t=Helper.unification.deviceFieldsUnification(t),e.push({deviceName:t.name,alias:t.alias,status:Helper.template.connectionStatusBadge(t.connection_state),ip:`<code class="code">${t.ip}</code>`,actions:`
				<button 
					class="btn btn-secondary btn-small details-btn" 
					data-device='${JSON.stringify(t)}'
					type="button"
				>Details</button>

				<button 
					class="btn btn-warning btn-small reboot-btn" 
					data-device-id="${t.id}" 
					data-device-name="${t.name}" 
					data-device-alias="${t.alias}" 
					type="button"
				>Reboot</button>
			`});return e}function lt(a,e,t){a.currentScreen.DOMObject.querySelector(".main-container").innerHTML=Helper.template.table("Devices list",{deviceName:"Device name",alias:"Device alias",status:"Status",ip:"IP",actions:"Actions"},e,`<span class="table-meta">Total: <span class="total">${t}</span> devices</span>`)}function dt(a,e){a.currentScreen.DOMObject.querySelectorAll(".reboot-btn").forEach(t=>{t.addEventListener("click",n=>{n.currentTarget.getAttribute("disabled")||y(e,n.currentTarget)})}),a.currentScreen.DOMObject.querySelectorAll(".details-btn").forEach(t=>{t.addEventListener("click",n=>{let s=b({status:""},JSON.parse(n.currentTarget.dataset.device));ue(s,e).show()})})}function pe(a){return{alias:"devices",renderer:()=>Helper.template.mainTemplate(C("devices")),initer:e=>{a.devices.list((t,n,s)=>{if(console.log("sh_api.devices.list",t,n,s),s.status_code!=200)return e.error("Server API ERROR","");lt(e,ct(n.data),n.data.total),dt(e,a),e.ready()})}}}function me(a,e){return a=Helper.unification.deviceFieldsUnification(a),Modals.create("device-setup",{title:`Setup new device ${a.ip}`,body:t=>{let n="";for(let r in a)r[0]!="_"&&(n+=`
					<tr class="table-row">
						<th>${r}: </th>
						<td>${a[r]}</td>
					</tr>
				`);return`
				<div class="row g-6">
					<div class="col device-info">
						${`
				<div class="block">
					<table class="table" style="border: 0">
						<tbody class="table-body">
							${n}
						</tbody>
					</table>
				</div>
			`}
					</div>

					<div class="col setup-form w-100">
						<div class="block form-group">
							<label class="label">
								Device alias
								<i class="ph ph-asterisk"></i>
								<input type="text" name="alias" class="input" placeholder="Input alias">
							</label>
						</div>

						<div class="block form-group">
							<label class="label">
								Device name
								<i class="ph ph-asterisk"></i>
								<input type="text" name="name" class="input" placeholder="Input name">
							</label>
						</div>

						<div class="block form-group">
							<label class="label">
								About device
								<i class="ph ph-note-pencil"></i>
								<textarea class="input" name="description" placeholder="Input description"></textarea>
							</label>
						</div>

						<div class="alert-container"></div>
					</div>
				</div>
			`},actions:t=>{let n=Helper.template.createElement("button",{class:"btn btn-primary"},"Cancel");n.addEventListener("click",r=>{t.close()});let s=Helper.template.createElement("button",{class:"btn btn-success with-icon"},'<i class="ph ph-gear"></i> Setup');return s.addEventListener("click",r=>{if(r.currentTarget.getAttribute("disabled"))return!1;let o={device_ip:a.ip},i=document.querySelector("#device-setup .setup-form");if(i.querySelectorAll("input[type='text']").forEach(d=>{d.dispatchEvent(new Event("input",{bubbles:!0}))}),i.querySelectorAll(".label.error").length)return!1;let c=i.querySelectorAll("input"),l=i.querySelector("textarea");for(let d of c)o[d.getAttribute("name")]=d.value;o[l.getAttribute("name")]=l.value,Helper.states.btnLoadingState(s,!0),e.devices.setup_new_device(o,(d,p,m)=>{var u,h;if(Helper.states.btnLoadingState(s,!1),(d==null?void 0:d.type)=="api_error"){if(console.error("ERR! sh_api.devices.setup_new_device",d.raw),(u=d.raw)!=null&&u.failed_fields)for(let v of d.raw.failed_fields)t.querySelector(`[name="${v}"]`).parentNode.classList.add("error");if((h=d.raw)!=null&&h.msg){let v=t.querySelector(".setup-form .alert-container");v.innerHTML="",v==null||v.append(Helper.template.createAlert("error",d.raw.msg))}return!1}if(!p)return!1;c.forEach(v=>v.value=""),l.value="",t.close(),Screens.reinit(),setTimeout(()=>{Toasts.createSuccess("Setup successful",`Added new device <b>ID ${a.device_id}</b>`).show()},300)})}),[n,s]},onready:t=>{t.querySelector(".setup-form").querySelectorAll("input").forEach(s=>{s.addEventListener("input",r=>{var o;r.currentTarget.value.length?(r.currentTarget.parentNode.classList.remove("error"),(o=r.currentTarget.parentNode.parentNode.querySelector(".input-info.error"))==null||o.remove()):(r.currentTarget.parentNode.classList.add("error"),r.currentTarget.parentNode.parentNode.querySelector(".input-info.error")||r.currentTarget.parentNode.parentNode.append(Helper.template.createElement("div",{class:"input-info error"},'<i class="ph ph-warning-circle"></i> Field cannot be empty')))})})}})}function ut(a){let e=[];for(let t of a.devices)t=Helper.unification.deviceFieldsUnification(t),e.push({deviceId:t.device_id,deviceName:t.name,deviceType:t.type,status:`<span class="badge badge-primary">${t.status}</span>`,ip:`<code class="code">${t.ip}</code>`,mac:`<code class="code">${t.mac}</code>`,wifiSignal:t.wifi_signal,actions:t.status=="setup"?`
				<button 
					class="btn btn-secondary btn-small setup-btn" 
					data-device='${JSON.stringify(t)}'
					type="button"
				>Setup</button>
			`:""});return e}function pt(a,e,t){a.currentScreen.DOMObject.querySelector(".main-container").innerHTML=Helper.template.table("Found devices",{deviceId:"Device ID",deviceName:"Device name",deviceType:"Type",status:"Status",ip:"IP",mac:"Mac",wifiSignal:"Signal",actions:"Actions"},e,`<span class="table-meta">Total: <span class="total">${t}</span> devices</span>`)}function mt(a,e){a.currentScreen.DOMObject.querySelectorAll(".setup-btn").forEach(t=>{t.addEventListener("click",n=>{let s=JSON.parse(n.currentTarget.dataset.device);me(s,e).show()})})}function fe(a){return{alias:"devices-scanning",renderer:()=>Helper.template.mainTemplate(C("scanning")),initer:e=>{a.devices.scanning_all((t,n,s)=>{if(console.log("sh_api.devices.scanning_all",t,n),s.status_code!=200)return e.error("Server API ERROR","");pt(e,ut(n.data),n.data.devices.length),mt(e,a),e.ready()})}}}var B={list:pe,scanning:fe};function L(a){return Helper.template.sidebarNav([{content:'<span class="list-label"><i class="ph ph-cpu"></i> Scopes</span>',route:"/#!/scripts/scopes",is_active:a=="scopes"},{content:'<span class="list-label"><i class="ph ph-play"></i> Actions</span>',route:"/#!/scripts/actions",is_active:a=="actions"},{content:'<span class="list-label"><i class="ph ph-magnifying-glass"></i> Regular</span>',route:"/#!/scripts/regular",is_active:a=="regular"}])}function z(a,e,t){a.scripts.run({alias:e,params:{}},(n,s,r)=>{s?(t(!0),setTimeout(()=>Screens.reinit(),1e3),setTimeout(()=>Toasts.createSuccess(`${e} running`,`<b>${e}</b> running success`).show(),300)):(t(!1),setTimeout(()=>Toasts.createError(`${e} failed`,`<b>${e}</b> running failed`).show(),300))})}function J(a){return`
		<div 
			class="card device-action card-${a.state=="enabled"?"primary":"warning"} script-action" 
			data-alias="${a.alias}"
		>
			<span class="card-title">${a.name} 
				<button 
					class="btn-icon without-hover action-details-btn" 
					data-alias='${a.alias}'
				>
					<i class="ph ph-dots-three-vertical"></i>
				</button>
			</span>

			<div class="card-content">
				<div class="device-icon-container">
					<div class="device-icon">
						${a.icon}
					</div>
				</div>

				<div class="device-name mb-2">${a.description}</div>
			</div>
		</div>
	`}function V(a,e){e.querySelector(".card-content").addEventListener("click",t=>{if(e.getAttribute("disabled"))return;Helper.states.cardScriptActionLoadingState(e,!0);let n=e.dataset.alias;z(a,n,s=>{Helper.states.cardScriptActionLoadingState(e,!1),s&&(e.classList.add("card-success"),setTimeout(()=>e.classList.remove("card-success"),1e3))})})}function ve(a,e){let t=document.createElement("div");t.innerHTML=J(e);let n=t.querySelector(".card");return V(a,n),n}function ft(a){let e=[];for(let t of a.scopes){let n=t.state=="disabled"?`<button 
					class="btn btn-success btn-small change-state-btn" 
					data-scope='${JSON.stringify(t)}'
					type="button"
					data-value="enable"
				>Enable</button>`:`<button 
					class="btn btn-warning btn-small change-state-btn" 
					data-scope='${JSON.stringify(t)}'
					type="button"
					data-value="disable"
				>Disable</button>`;e.push({name:t.name,filename:`${t.filename}<br><code><small>${t.path}</small></code>`,state:Helper.template.toogleStateBadge(t.state),actions:`
				${n}
			`})}return e}function vt(a,e,t){a.currentScreen.DOMObject.querySelector(".main-container").innerHTML=Helper.template.table("Scopes list",{name:"Scope name",filename:"Filename",state:"State",actions:"Actions"},e,`<span class="table-meta">Total: <span class="total">${t}</span> scopes</span>`)}function bt(a,e){a.currentScreen.DOMObject.querySelectorAll(".change-state-btn").forEach(t=>{t.addEventListener("click",n=>{let s=n.currentTarget;if(s.getAttribute("disabled"))return;let r=s.dataset.value=="enable"?"scope_enable":"scope_disable",o=JSON.parse(s.dataset.scope);Helper.states.btnLoadingState(s,!0),e.scripts[r](o.name,(i,c,l)=>{Helper.states.btnLoadingState(s,!1),c?(setTimeout(()=>Screens.reinit(),250),Toasts.createSuccess("Request Success",`State of <b>${o.name}</b> was changed`).show()):Toasts.createError("Request failed","Scope state not changed").show()})})})}function be(a){return{title:"Scripts Scopes",alias:"scripts-scopes",renderer:()=>Helper.template.mainTemplate(L("scopes")),initer:e=>{a.scripts.scopes_list((t,n,s)=>{if(console.log("sh_api.scripts.scopes_list",t,n,s),s.status_code!=200)return e.error("Server API ERROR","");vt(e,ft(n.data),n.data.total),bt(e,a),e.ready()})}}}function ht(a){let e=[];for(let t of a.scripts){let n=t.state=="disabled"?`<button 
					class="btn btn-success btn-small change-state-btn" 
					data-alias='${t.alias}'
					type="button"
					data-value="enable"
				>Enable</button>`:`<button 
					class="btn btn-warning btn-small change-state-btn" 
					data-alias='${t.alias}'
					type="button"
					data-value="disable"
				>Disable</button>`;e.push({alias:`${t.alias}<br><small class="text-muted">by ${t.created_by}</small>`,name:`${t.name}<div class="mt-1"><small>${t.description}</small></div>`,filename:`${t.filename}<br><code><small>${t.path}</small></code>`,state:Helper.template.toogleStateBadge(t.state),actions:`
				${n}
			`})}return e}function gt(a,e,t){let n={};for(let s in e)n[e[s].alias]=e[s],e[s].code="";a.currentScreen.DOMObject.provideSciptsData=n,a.currentScreen.DOMObject.querySelector(".main-container").innerHTML=Helper.template.table("Regular scripts list",{alias:"Alias",name:"Script name",filename:"Filename",state:"State",actions:"Actions"},e,`<span class="table-meta">Total: <span class="total">${t}</span> scripts</span>`)}function St(a,e){a.currentScreen.DOMObject.querySelectorAll(".change-state-btn").forEach(t=>{t.addEventListener("click",n=>{var i;let s=n.currentTarget;if(s.getAttribute("disabled"))return;let r=s.dataset.value=="enable"?"regular_enable":"regular_disable",o=(i=a.currentScreen.DOMObject.provideSciptsData[s.dataset.alias])!=null?i:{};Helper.states.btnLoadingState(s,!0),e.scripts[r](o.alias,(c,l,d)=>{Helper.states.btnLoadingState(s,!1),l?(setTimeout(()=>Screens.reinit(),250),Toasts.createSuccess("Request Success",`State of <b>${o.alias}</b> was changed`).show()):Toasts.createError("Request failed","Regular script state not changed").show()})})})}function he(a){return{title:"Scripts Regular",alias:"scripts-regular",renderer:()=>Helper.template.mainTemplate(L("regular")),initer:e=>{a.scripts.regular_list((t,n,s)=>{if(console.log("sh_api.scripts.regular_list",t,n,s),s.status_code!=200)return e.error("Server API ERROR","");gt(e,ht(n.data),n.data.total),St(e,a),e.ready()})}}}function ge(a,e){return console.log("actionDetailsPopup",a),Modals.create("action-script-popup",{title:`${a.name}`,body:t=>{let n=a.area_id!=-1?'<div class="mt-8 mb-8 place-in-area-component-container"></div>':"";return`
				<div class="block">
					<div class="row g-4">
						<div class="col script-info w-100">
							<h4 class="alias"><i class="ph ph-link-simple-break normalize"></i> <code>${a.alias}</code></h4>
							<div class="description mt-3">${a.description}</div>
							<div class="state mt-10">${Helper.template.toogleStateBadge(a.state)}</div>
							${n}
							<div class="filename mt-4"><i class="ph ph-file-code normalize"></i> ${a.filename}</div>
							<div class="author mt-4 text-muted"><i class="ph ph-user normalize"></i> By ${a.author}</div>
						</div>
						<div class="col script-code w-200">
							<div class="script-code-view">
								<pre><code class="language-php code-viewer fs-xs">${a.code}</code></pre>
							</div>
						</div>
					</div>
				</div>
			`},actions:t=>{let n=Helper.template.createElement("button",{class:"btn btn-primary"},"Close"),s=Helper.template.createElement("button",{class:a.state=="enabled"?"btn btn-warning":"btn btn-success","data-value":a.state=="enabled"?"disable":"enable"},a.state=="enabled"?"Disable":"Enable"),r=Helper.template.createElement("button",{class:"btn btn-secondary with-icon"},'<i class="ph ph-play"></i> Run');return n.addEventListener("click",o=>{t.close()}),s.addEventListener("click",o=>{let i=o.currentTarget;if(i.getAttribute("disabled"))return;let c=i.dataset.value=="enable"?"action_enable":"action_disable";Helper.states.btnLoadingState(i,!0),e.scripts[c](a.alias,(l,d,p)=>{Helper.states.btnLoadingState(i,!1),t.close(),d?(setTimeout(()=>Screens.reinit(),250),Toasts.createSuccess("Request Success",`State of <b>${a.alias}</b> was changed`).show()):Toasts.createError("Request failed","Regular script state not changed").show()})}),r.addEventListener("click",o=>{let i=o.currentTarget;Helper.states.btnLoadingState(i,!0),z(e,a.alias,c=>{Helper.states.btnLoadingState(i,!1),c&&t.close()})}),[n,s,r]},onready:t=>{w(e,t.querySelector(".place-in-area-component-container"),"action",a.id,a.area_id),hljs.highlightElement(t.querySelector(".code-viewer"))}})}function W(a){var t,n,s;let e=[];for(let r of a.scripts)e.push({alias:r.alias,author:r.created_by,name:r.name,icon:(t=r.icon)!=null?t:'<i class="ph ph-play"></i>',description:r.description,filename:`${r.filename}<br><code><small>${r.path}</small></code>`,state:r.state,code:r.code,id:(n=r.id)!=null?n:0,area_id:(s=r.area_id)!=null?s:-1});return e}function yt(a,e,t){let n='<div class="f-grid g-5 w-100">',s={};for(let o of e)s[o.alias]=o,n+=J(o);n+="</div>";let r=a.currentScreen.DOMObject.querySelector(".main-container");r.innerHTML=n,a.currentScreen.DOMObject.provideSciptsData=s}function _t(a,e){a.currentScreen.DOMObject.querySelectorAll(".script-action").forEach(t=>{V(e,t)}),a.currentScreen.DOMObject.querySelectorAll(".action-details-btn").forEach(t=>{t.addEventListener("click",n=>{var o;let s=n.currentTarget,r=(o=a.currentScreen.DOMObject.provideSciptsData[s.dataset.alias])!=null?o:{};console.log("SCRIPT",r),ge(r,e).show()})})}function Se(a){return{title:"Scripts Actions",alias:"scripts-actions",renderer:()=>Helper.template.mainTemplate(L("actions")),initer:e=>{a.scripts.actions_list((t,n,s)=>{if(console.log("sh_api.scripts.actions_list",t,n,s),s.status_code!=200)return e.error("Server API ERROR","");yt(e,W(n.data),n.data.total),_t(e,a),e.ready()})}}}var R={scopes:be,regular:he,actions:Se};function ye(a){return Helper.template.sidebarNav([{content:'<span class="list-label"><i class="ph ph-tree-structure"></i> Areas Tree</span>',route:"/#!/areas/tree",is_active:a=="areas-tree"}])}function _e(a,e){return console.log("areaDevicesModal",a),Modals.create("area-devices-modal",{title:`<i class="ph ph-map-trifold normalize"></i> ${a.display_name}`,body:t=>`
				<div class="loader"></div>
				<div class="devices-container h-100"></div>
			`,actions:t=>{let n=Helper.template.createElement("button",{class:"btn btn-primary"},"Close"),s=Helper.template.createElement("button",{class:"btn btn-warning with-icon btn-reboot-all"},'<i class="ph ph-arrow-clockwise"></i> Reboot All');return n.addEventListener("click",r=>{t.close()}),s.addEventListener("click",r=>{s.getAttribute("disabled")||(Helper.states.btnLoadingState(s,!0),confirmPopup(`Are you sure you want to reboot all devices from <b>${a.display_name}</b>?`,()=>{e.areas.reboot_devices(a.id,(o,i,c)=>{Helper.states.btnLoadingState(s,!1),i?(console.log("Was rebooted all devices"),Toasts.createSuccess("Rebooted all devices",`Area: <b>${a.display_name}</b>`).show()):Toasts.createDanger("Rebooted fail",`Area: <b>${a.display_name}</b>`).show()})},()=>{Helper.states.btnLoadingState(s,!1),console.log("CANCELED")}))}),[n,s]},onready:t=>{let n=t.querySelector(".devices-container"),s=t.querySelector(".loader");e.areas.devices(a.id,(r,o,i)=>{console.log("sh_api.areas.devices",o);function c(d){if(!d)return[];let p=[];for(let m of d.devices)m=Helper.unification.deviceFieldsUnification(m),p.push({deviceName:m.name,alias:m.alias,status:Helper.template.connectionStatusBadge(m.connection_state),ip:`<code class="code">${m.ip}</code>`,actions:`
								<button 
									class="btn btn-warning btn-small reboot-btn" 
									data-device-id="${m.id}" 
									data-device-name="${m.name}" 
									data-device-alias="${m.alias}" 
									type="button"
								>Reboot</button>
							`});return p}let l=c(o==null?void 0:o.data);l.length?n.innerHTML=Helper.template.table("",{deviceName:"Device name",alias:"Device alias",status:"Status",ip:"IP",actions:"Actions"},l,`<span class="table-meta">Total: <span class="total">${l.length}</span> devices</span>`):(n.innerHTML=Helper.template.emptyHereHTML(),t.querySelector(".btn-reboot-all").remove()),n.querySelectorAll(".reboot-btn").forEach(d=>{d.addEventListener("click",p=>{d.getAttribute("disabled")||y(e,p.currentTarget,t)})}),s.remove(),console.log("devices",l)})}})}function we(a,e){return console.log("areaActionsModal",a),Modals.create("area-actions-modal",{title:`<i class="ph ph-map-trifold normalize"></i> ${a.display_name}`,body:t=>`
				<div class="loader"></div>
				<div class="actions-container f-grid g-4 h-100">
				</div>
			`,actions:t=>{let n=Helper.template.createElement("button",{class:"btn btn-primary"},"Close");return n.addEventListener("click",s=>{t.close()}),[n]},onready:t=>{let n=t.querySelector(".actions-container"),s=t.querySelector(".loader");e.areas.scripts(a.id,(r,o,i)=>{if(console.log("sh_api.areas.scripts",r,o,i),i.status_code!=200)return Toasts.createDanger("Loading failed",`Area: <b>${a.display_name}</b>`).show();let c=W(o.data);n.innerHTML="",c.length||(n.innerHTML=Helper.template.emptyHereHTML()),s.remove();for(let l of c)n.append(ve(e,l))})}})}function Le(a){return console.log("createNewAreaModal"),Modals.create("create-area-modal",{title:'<i class="ph ph-plus normalize"></i> Create new Area',body:e=>`
				<div class="create-area-form">
					<div class="block form-group">
						<label class="label">
							Type
							<input type="text" class="input" name="type" placeholder="Input Area Type">
						</label>
						<div class="advanced-select-container"></div>
					</div>

					<div class="block form-group">
						<label class="label">
							Alias
							<i class="ph ph-link-simple-break"></i>
							<input type="text" class="input" name="alias" placeholder="Input Area Alias">
						</label>
					</div>

					<div class="block form-group">
						<label class="label">
							Display Name
							<i class="ph ph-tag"></i>
							<input type="text" class="input" name="display_name" placeholder="Input Display Name">
						</label>
					</div>

					<div class="alert-container"></div>
				</div>
			`,actions:e=>{let t=Helper.template.createElement("button",{class:"btn btn-primary"},"Close"),n=Helper.template.createElement("button",{class:"btn btn-success with-icon"},'<i class="ph ph-plus"></i> Create');return t.addEventListener("click",s=>{e.close()}),n.addEventListener("click",s=>{let r=e.querySelector(".create-area-form");if(r.querySelectorAll("input[type='text']").forEach(c=>{c.dispatchEvent(new Event("input",{bubbles:!0}))}),r.querySelectorAll(".label.error").length)return!1;let o=r.querySelectorAll("input"),i={};for(let c of o)i[c.getAttribute("name")]=c.value;Helper.states.btnLoadingState(n,!0),a.areas.new_area(i,(c,l,d)=>{var p,m;if(Helper.states.btnLoadingState(n,!1),(c==null?void 0:c.type)=="api_error"){if(console.error("ERR! sh_api.areas.new_area",c.raw),(p=c.raw)!=null&&p.failed_fields)for(let u of c.raw.failed_fields)e.querySelector(`[name="${u}"]`).parentNode.classList.add("error");if((m=c.raw)!=null&&m.msg){let u=e.querySelector(".alert-container");u.innerHTML="",u==null||u.append(Helper.template.createAlert("error",c.raw.msg))}return!1}if(!l)return!1;o.forEach(u=>u.value=""),e.close(),Screens.reinit(),setTimeout(()=>{Toasts.createSuccess("Creating successful",`Added new area <b>ID ${i.alias}</b>`).show()},300)})}),[t,n]},onready:e=>{let t=e.querySelector(".create-area-form");t.querySelectorAll(".input").forEach(n=>{n.addEventListener("input",s=>{var r;s.currentTarget.value.length?(s.currentTarget.parentNode.classList.remove("error"),(r=s.currentTarget.parentNode.parentNode.querySelector(".input-info.error"))==null||r.remove()):(s.currentTarget.parentNode.classList.add("error"),s.currentTarget.parentNode.parentNode.querySelector(".input-info.error")||s.currentTarget.parentNode.parentNode.append(Helper.template.createElement("div",{class:"input-info error"},'<i class="ph ph-warning-circle"></i> Field cannot be empty')))})}),a.areas.types_list((n,s,r)=>{console.log("sh_api.areas.types_list",n,s,r),s||console.error("Request Error. sh_api.areas.types_list()");let o={};for(let i of s.data.types)o[i]=i;t.querySelector(".advanced-select-container").append(advancedSelect(t.querySelector('[name="type"]'),o,"Will be created"))})}})}function Ee(a,e){return console.log("areaDetailsModal",a),Modals.create("area-details-modal",{title:`<i class="ph ph-map-trifold normalize"></i> ${a.display_name}`,body:t=>`
				<div class="place-in-area-container"></div>
			`,actions:t=>{let n=Helper.template.createElement("button",{class:"btn btn-primary"},"Close"),s=Helper.template.createElement("button",{class:"btn btn-danger with-icon"},'<i class="ph ph-trash"></i> Remove');return n.addEventListener("click",r=>{t.close()}),s.addEventListener("click",r=>{Helper.states.btnLoadingState(s,!0),confirmPopup(`Are you sure you want to remove this area? <b>${a.display_name}</b>`,()=>{e.areas.remove(a.id,(o,i,c)=>{Helper.states.btnLoadingState(s,!1),console.log("Was removed"),t.close(),Screens.reinit(),setTimeout(()=>{Toasts.createSuccess("Removed",`Area: ${a.display_name}`).show()},300)})},()=>{Helper.states.btnLoadingState(s,!1),console.log("CANCELED")})}),[n,s]},onready:t=>{w(e,t.querySelector(".place-in-area-container"),"area",a.id,a.parent_id)}})}function wt(a){let e=a.areas,t={},n=[];for(let s of e)t[s.id]=ee(b({},s),{children:[]});for(let s of e){let r=t[s.id];s.parent_id&&t[s.parent_id]?t[s.parent_id].children.push(r):n.push(r)}return n}function Lt(a){return wt(a)}function $e(a,e){var s,r;e=e!=null?e:0;let t=(s=a.children)!=null&&s.length?"":"is-single",n=`
		<div class="branch lvl-${e} ${t}" data-lvl="${e}">
			<button class="btn-icon without-hover show-childs">
				<i class="ph ph-caret-right"></i>
			</button>
			<div class="branch-container">
				<div class="branch-info">
					<span class="title"><i class="ph ph-map-trifold normalize"></i> ${a.display_name}</span>
					[
					<span class="text-muted area-type">${a.type}</span>
					<span><i class="ph ph-link-simple-break normalize"></i> ${a.alias}</span>
					]
				</div>

				<div class="row g-4">
					<button 
						class="btn btn-accent btn-small with-icon actions"
						data-area-id="${a.id}"
						data-area-name="${a.display_name}"
					><i class="ph ph-brackets-curly"></i> Actions</button>
					<button 
						class="btn btn-accent btn-small with-icon devices" 
						data-area-id="${a.id}"
						data-area-name="${a.display_name}"
					><i class="ph ph-cpu"></i> Devices</button>
					<button 
						class="btn btn-small btn-primary details"
						data-area-id="${a.id}"
						data-area-name="${a.display_name}"
						data-parent-id="${a.parent_id}"
					>Details</button>
				</div>
			</div>
		</div>
	`;if((r=a.children)!=null&&r.length)for(let o of a.children)n+=$e(o,e+1);return n}function Et(a,e){console.log("TREE",e);let t='<div class="tree">';for(let n of e)t+=$e(n);t+="</div>",a.currentScreen.DOMObject.querySelector(".main-container .tree-container").innerHTML=t}function $t(a,e){a.currentScreen.DOMObject.querySelectorAll(".btn.devices").forEach(t=>{t.addEventListener("click",n=>{_e({id:n.currentTarget.dataset.areaId,display_name:n.currentTarget.dataset.areaName},e).show()})}),a.currentScreen.DOMObject.querySelectorAll(".btn.actions").forEach(t=>{t.addEventListener("click",n=>{we({id:n.currentTarget.dataset.areaId,display_name:n.currentTarget.dataset.areaName},e).show()})}),a.currentScreen.DOMObject.querySelectorAll(".btn.details").forEach(t=>{t.addEventListener("click",n=>{Ee({id:n.currentTarget.dataset.areaId,display_name:n.currentTarget.dataset.areaName,parent_id:n.currentTarget.dataset.parentId},e).show()})}),a.currentScreen.DOMObject.querySelectorAll("button.show-childs").forEach(t=>{t.addEventListener("click",n=>{let s=n.currentTarget,r=s.parentNode,o=parseInt(r.dataset.lvl);if(s.classList.contains("opened")){s.classList.remove("opened");let i=r.nextElementSibling;for(;i;){let c=parseInt(i.dataset.lvl);if(c==o||c<o)break;c==o+1&&i.classList.remove("a-show"),i=i.nextElementSibling}}else{s.classList.add("opened");let i=r.nextElementSibling;for(;i;){let c=parseInt(i.dataset.lvl);if(c==o||c<o)break;c==o+1&&i.classList.add("a-show"),i=i.nextElementSibling}}})}),a.ready()}function Te(a){return{title:"Areas Tree",alias:"areas-tree",renderer:()=>Helper.template.mainTemplate(ye("areas-tree"),`<div class="top-bar">
					<div class="row g-4">
						<div class="col">
							<h3 class="title">Areas Tree</h3>
						</div>
						<div class="col">
							<button class="btn btn-primary with-icon create-new-area-modal">
								<i class="ph ph-plus"></i>
								Create
							</button>
						</div>
					</div>
				</div>
				<div class="mt-6 tree-container"></div>
				`),initer:e=>{a.areas.list((t,n,s)=>{var r;if(console.log("sh_api.areas.list",t,n,s),s.status_code!=200)return e.error("Server API ERROR","");Et(e,Lt(n.data)),$t(e,a),(r=e.currentScreen.DOMObject.querySelector(".create-new-area-modal:not(.inited)"))==null||r.addEventListener("click",o=>{o.currentTarget.classList.add("inited"),Le(a).show()}),e.ready()})}}}var He={areasTree:Te};function Ae(a,e){a.add("/",{alias:"home",renderer:()=>"",initer:t=>{document.location="/#!/areas/tree"}}),a.add("-",{alias:"not-found-screen",renderer:()=>'<h2 class="mt-4">404 NOT FOUND</h2>',initer:t=>{t.ready()}}),a.add("/devices",B.list(e)),a.add("/devices/scanning",B.scanning(e)),a.add("/scripts/scopes",R.scopes(e)),a.add("/scripts/regular",R.regular(e)),a.add("/scripts/actions",R.actions(e)),a.add("/areas/tree",He.areasTree(e))}function Tt(a,e,t){return`
		<div class="modal" aria-hidden="true" id="${a}">
      <div class="modal-backdrop"></div>

      <div class="modal-panel" role="dialog" aria-modal="true" aria-labelledby="modal-title-basic">
        <header class="modal-header">
          <h4 class="modal-title" id="modal-title-basic">${e}</h4>
          <button class="btn-icon modal-close" type="button" aria-label="Close">\u2715</button>
        </header>

        <div class="modal-body"></div>
        <footer class="modal-footer">${t}</footer>
      </div>
    </div>
	`}function Ht(a,e){return a.show=function(){document.querySelector("body").append(a),setTimeout(()=>{a.classList.add("a-show")},10)},a.close=function(){a.classList.add("a-hide"),setTimeout(()=>{a.remove()},300)},a.querySelector(".modal-close").addEventListener("click",t=>{a.close()}),typeof e=="function"&&e(a),a}function At(a,e){let t=e.title||"",n=e.footer||"",s=document.createElement("div");s.innerHTML=Tt(a,t,n);let r=s.childNodes[1],o=r.querySelector(".modal-body"),i=r.querySelector(".modal-footer");if(typeof e.actions=="function"){let c=e.actions(r);if(typeof c[0]=="object"){let l=document.createElement("div");l.classList.add("actions");for(let d of c)l.append(d);i.append(l)}}if(typeof e.body=="function"){let c=e.body(r);typeof c=="object"?o.append(c):typeof c=="string"&&(o.innerHTML=c)}return Ht(r,e==null?void 0:e.onready)}var Me={create:At};function Y(a,e,t){Modals.create("confirm-popup",{title:"Requires confirmation",body:n=>`
				<p>${a}</p>
			`,actions:n=>{let s=Helper.template.createElement("button",{class:"btn btn-primary"},"NO"),r=Helper.template.createElement("button",{class:"btn btn-warning"},"YES");return s.addEventListener("click",o=>{n.close(),t()}),r.addEventListener("click",o=>{n.close(),e()}),[s,r]}}).show()}function De(a){let e=a.querySelector(".focus");if(!e)return;let t=a.getBoundingClientRect(),n=e.getBoundingClientRect();n.top<t.top?a.scrollTop-=t.top-n.top:n.bottom>t.bottom&&(a.scrollTop+=n.bottom-t.bottom)}function G(a){a.advancedSelect.optionsElements.length-a.querySelectorAll(".option.hide").length==0?a.advancedSelect.showState("not-found"):a.advancedSelect.showState("options")}function K(a,e,t){let n=document.createElement("div");n.classList.add("advanced-select");let s="";for(let i in e)s+=`<div class="option" data-value="${i}" data-display-value="${e[i]}">${e[i]}</div>`;let r=`
		<div class="popup-options-container">
			<div class="not-found">${t}</div>
			<div class="options">${s}</div>
		</div>
	`;n.innerHTML=r;let o=(i,c)=>{for(let l in c)if(c[l]==i){let d={};return d[l]=c[l],d}return!1};return n.advancedSelect={isOpened:!1,options:e,eventsHandlers:{openList:[],closeList:[],selected:[],changed:[]},openList:()=>{n.advancedSelect.isOpened=!0,n.classList.add("a-show"),G(n),n.advancedSelect.dispatchEvent("openList")},closeList:()=>{n.advancedSelect.isOpened=!1,n.classList.remove("a-show"),G(n),n.advancedSelect.dispatchEvent("closeList")},showState:i=>{i=="options"?(n.querySelector(".options").classList.add("show"),n.querySelector(".not-found").classList.remove("show")):i=="not-found"&&(n.querySelector(".options").classList.remove("show"),n.querySelector(".not-found").classList.add("show"))},optionsElements:n.querySelectorAll(".option"),value:()=>{let i=o(a.value,e);return{inputValue:a.value,isOption:!!i,option:i}},addEventListener:(i,c)=>{if(typeof n.advancedSelect.eventsHandlers[i]!="undefined")return n.advancedSelect.eventsHandlers[i].push(c);console.error("Advanced Select component.","addEventListener()","Invalid event name")},dispatchEvent:i=>{if(typeof n.advancedSelect.eventsHandlers[i]=="undefined")return console.error("Advanced Select component.","dispatchEvent()","Invalid event name");for(let c of n.advancedSelect.eventsHandlers[i])c(n)}},a.setAttribute("autocomplete","nope"),a.advancedSelect={value:()=>n.advancedSelect.value()},a.addEventListener("focus",i=>{n.advancedSelect.openList()}),a.addEventListener("blur",i=>{setTimeout(()=>n.advancedSelect.closeList(),20)}),a.addEventListener("keydown",i=>{if(i.keyCode==38){let c=n.querySelector(".option.focus");if(c){c.classList.remove("focus");let l=c.previousElementSibling;for(;l&&l.classList.contains("hide");)l=l.previousElementSibling;l||(l=n.querySelector(".option:not(.hide)")),l.classList.add("focus")}else n.querySelector(".option:not(.hide):last-child").classList.add("focus");De(n)}else if(i.keyCode==40){let c=n.querySelector(".option.focus");if(c){c.classList.remove("focus");let l=c.nextElementSibling;for(;l&&l.classList.contains("hide");)l=l.nextElementSibling;l||(l=n.querySelector(".option:not(.hide)")),l.classList.add("focus")}else n.querySelector(".option:not(.hide)").classList.add("focus");De(n)}else if(i.keyCode==13){let c=n.querySelector(".option.focus");if(!c)return;a.value=c.dataset.displayValue,a.blur(),a.dispatchEvent(new Event("input",{bubbles:!0})),a.dispatchEvent(new Event("change",{bubbles:!0})),n.advancedSelect.dispatchEvent("selected")}}),a.addEventListener("input",i=>{var l;let c=i.currentTarget.value.toLowerCase();c==""?n.advancedSelect.optionsElements.forEach(d=>d.classList.remove("hide")):([...n.advancedSelect.optionsElements].filter(d=>d.dataset.displayValue.toLowerCase().indexOf(c)!=-1).forEach(d=>d.classList.remove("hide")),[...n.advancedSelect.optionsElements].filter(d=>d.dataset.displayValue.toLowerCase().indexOf(c)==-1).forEach(d=>d.classList.add("hide")),G(n),(l=n.querySelector(".option.focus"))==null||l.classList.remove("focus"))}),a.addEventListener("change",i=>{n.advancedSelect.dispatchEvent("changed")}),[...n.advancedSelect.optionsElements].forEach(i=>{i.addEventListener("click",c=>{a.value=c.currentTarget.dataset.displayValue,a.blur(),a.dispatchEvent(new Event("input",{bubbles:!0})),a.dispatchEvent(new Event("change",{bubbles:!0})),n.advancedSelect.dispatchEvent("selected")})}),n}document.addEventListener("DOMContentLoaded",a=>{console.log("App init"),document.location.hash.indexOf("#!/")==-1&&(document.location.hash="#!/"),window.Toasts=re,window.Helper=oe,window.Modals=Me,window.confirmPopup=Y,window.advancedSelect=K,ne();let e=new O({base_url:API_BASEURL,token:"YOUR_TOKEN",timeout_ms:3e3,on_unauthorized:({error:n})=>console.log("auth problem:",n),proxy_path:"/proxy.php"}),t=new A(".screens",".load-screen",".error-screen");Ae(t,e),console.log(t.getScreens()),t.onSwitch((n,s)=>{x()}),t.onSwitch((n,s,r)=>{var o;document.querySelectorAll(".app .hud .navigation .nav-link[data-route].active").forEach(i=>i.classList.remove("active")),(o=document.querySelector(`.app .hud .navigation .nav-link[data-route="${r}"]`))==null||o.classList.add("active")}),t.routing(),window.Screens=t});})();
//# sourceMappingURL=main.js.map
