var GatewayWidget_1,__decorate=this&&this.__decorate||function(t,e,n,i){var o,a=arguments.length,r=a<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(o=t[s])&&(r=(a<3?o(r):a>3?o(e,n,r):o(e,n))||r);return a>3&&r&&Object.defineProperty(e,n,r),r},__awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{l(i.next(t))}catch(t){a(t)}}function s(t){try{l(i.throw(t))}catch(t){a(t)}}function l(t){var e;t.done?o(t.value):((e=t.value)instanceof n?e:new n(function(t){t(e)})).then(r,s)}l((i=i.apply(t,e||[])).next())})};import{customElement as t,state as e}from"lit/decorators.js";import{OrWidget as n}from"../util/or-widget";import{css as i,html as o}from"lit";import{GatewaySettings as a}from"../settings/gateway-settings";import r from"@openremote/core";import{when as s}from"lit/directives/when.js";import{i18next as l}from"@openremote/or-translate";import{showSnackbar as d}from"@openremote/or-mwc-components/or-mwc-snackbar";import c from"moment";let styling=i`
    #gateway-widget-wrapper {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
    }

    #gateway-widget-container {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        max-height: 48px;
        flex-wrap: wrap;
        position: relative;
    }
`;function getDefaultWidgetConfig(){return{attributeRefs:[],type:"HTTPS",target:"localhost",targetPort:443}}let GatewayWidget=GatewayWidget_1=class extends n{constructor(){super(...arguments),this._loading=!0,this._isReady=!1,this._startedByUser=!1,this._refreshTimer=void 0}static getManifest(){return{displayName:"Gateway",displayIcon:"lan-connect",minColumnWidth:1,minColumnHeight:1,getContentHtml:t=>new GatewayWidget_1(t),getSettingsHtml:t=>new a(t),getDefaultConfig:()=>getDefaultWidgetConfig()}}refreshContent(t){this.widgetConfig=JSON.parse(JSON.stringify(this.widgetConfig)),this._readyCheck(this.widgetConfig)}static get styles(){return[...super.styles,styling]}disconnectedCallback(){this._refreshTimer&&clearTimeout(this._refreshTimer),super.disconnectedCallback()}firstUpdated(t){if(this.widgetConfig){let t=this._getTunnelInfoByConfig(this.widgetConfig);this._readyCheck(this.widgetConfig),setTimeout(()=>{this._getActiveTunnel(t).then(t=>{t&&(console.log("Existing tunnel found!",t),this._setActiveTunnel(t,!0))}).catch(t=>{console.error(t)}).finally(()=>{this._loading=!1})},500)}return super.firstUpdated(t)}render(){var t;this._getTunnelInfoByConfig(this.widgetConfig);let e=(null==(t=this.getEditMode)?void 0:t.call(this))||!this._isConfigComplete(this.widgetConfig)||!this._isReady;return o`
            <div id="gateway-widget-wrapper">
                <div id="gateway-widget-container">
                    ${s(this._loading,()=>o`
                        <or-loading-indicator></or-loading-indicator>
                    `,()=>{var t;return this._activeTunnel?o`
                                <div>
                                    <or-vaadin-button theme="primary" ?disabled=${e} @click=${t=>this._onStopTunnelClick(t)}>
                                        <or-icon slot="prefix" icon="stop"></or-icon>
                                        <or-translate value="gatewayTunnels.stop"></or-translate>
                                    </or-vaadin-button>
                                    
                                    ${s("TCP"===this.widgetConfig.type,()=>o`
                                        <or-vaadin-button ?disabled=${e} @click=${t=>this._onCopyTunnelAddressClick(t)}>
                                            <or-icon slot="prefix" icon="content-copy"></or-icon>
                                            <or-translate value="gatewayTunnels.copyAddress"></or-translate>
                                        </or-vaadin-button>
                                    `,()=>o`
                                        <or-vaadin-button ?disabled=${e} @click=${t=>this._onTunnelNavigateClick(t,this._activeTunnel)}>
                                            <or-icon slot="prefix" icon="open-in-new"></or-icon>
                                            <or-translate value="gatewayTunnels.open"></or-translate>
                                        </or-vaadin-button>
                                    `)}
                                </div>
                                ${s(null==(t=this._activeTunnel)?void 0:t.autoCloseTime,()=>{var t;return o`
                                    <div><or-translate value="gatewayTunnels.closesAt"></or-translate>: ${c(null==(t=this._activeTunnel)?void 0:t.autoCloseTime).format("lll")}</div>
                                `})}
                            `:o`
                                <or-vaadin-button ?disabled=${e} @click=${t=>this._onStartTunnelClick(t)}>
                                    <or-translate value=${e?"gatewayTunnels.offline":"gatewayTunnels.start"}></or-translate>
                                </or-vaadin-button>
                            `})}
                </div>
            </div>
        `}_onCopyTunnelAddressClick(t){if(this._isConfigComplete(this.widgetConfig)){let t=this._getTunnelInfoByConfig(this.widgetConfig),e=this._getTunnelAddress(t);e?navigator.clipboard.writeText(e).finally(()=>{d(void 0,l.t("gatewayTunnels.copySuccess"))}):(console.warn("Could not copy tunnel address as it could not be found."),d(void 0,l.t("errorOccurred")))}else console.warn("Could not copy tunnel address as configuration is not complete."),d(void 0,l.t("errorOccurred"))}_onStartTunnelClick(t){this._tryStartTunnel(this.widgetConfig)}_onStopTunnelClick(t){this._tryStopTunnel(this.widgetConfig)}_onTunnelNavigateClick(t,e){e?this._navigateToTunnel(e):console.warn("Could not navigate to tunnel as configuration is not complete.")}_setActiveTunnel(t,e=!1){if(this._activeTunnel=t,this._refreshTimer&&clearTimeout(this._refreshTimer),null==t?void 0:t.autoCloseTime){let e=(null==t?void 0:t.autoCloseTime)-Date.now();e>0&&(this._refreshTimer=window.setTimeout(()=>{this._getActiveTunnel(this._getTunnelInfoByConfig(this.widgetConfig)).then(t=>{t?this._setActiveTunnel(t,!0):this._setActiveTunnel(void 0)})},e))}t&&!e&&this._navigateToTunnel(t)}_tryStartTunnel(t){if(this._isConfigComplete(t)){let e=this._getTunnelInfoByConfig(t);this._loading=!0,this._getActiveTunnel(e).then(t=>{t?(console.log("Found an active tunnel!",t),this._setActiveTunnel(t),this._loading=!1):this._startTunnel(e).then(t=>{t?(console.log("Started a new tunnel!",t),this._setActiveTunnel(t),this._startedByUser=!0):console.warn("No new tunnel!")}).catch(t=>{console.error(t),d(void 0,l.t("errorOccurred"))}).finally(()=>{this._loading=!1})}).catch(t=>{console.error(t),d(void 0,l.t("errorOccurred")),this._loading=!1})}}_startTunnel(t){return __awaiter(this,void 0,void 0,function*(){if(!t.realm||!t.gatewayId||!t.target||!t.targetPort)throw Error("Could not start tunnel, as some provided information was not set.");return(yield r.rest.api.GatewayServiceResource.startTunnel(t)).data})}_getActiveTunnel(t){return __awaiter(this,void 0,void 0,function*(){if(!t.realm||!t.gatewayId||!t.target||!t.targetPort)throw Error("Could not get active tunnel, as some provided information was not set.");let e=yield r.rest.api.GatewayServiceResource.getActiveTunnelInfo(t.realm,t.gatewayId,t.target,t.targetPort);if(204!==e.status)return e.data})}_getGatewayStatus(t){return __awaiter(this,void 0,void 0,function*(){var e,n;if(t.gatewayId){let i=r.rest.api.AssetResource.get(t.gatewayId);i.catch(t=>console.error(t));let o=yield i;if(200===o.status)return null==(n=null==(e=o.data.attributes)?void 0:e.gatewayStatus)?void 0:n.value}})}_readyCheck(t){let e=this._getTunnelInfoByConfig(t);this._getGatewayStatus(e).then(t=>{this._isReady="CONNECTED"===t})}_tryStopTunnel(t){let e=this._getTunnelInfoByConfig(t);this._loading=!0,this._stopTunnel(e).then(()=>{this._setActiveTunnel(void 0),this._startedByUser=!1}).catch(t=>{console.warn(t)}).finally(()=>{this._loading=!1})}_stopTunnel(t){return __awaiter(this,void 0,void 0,function*(){return(yield r.rest.api.GatewayServiceResource.stopTunnel(t)).data})}_navigateToTunnel(t){var e;t.id&&t.realm&&t.gatewayId&&t.target&&t.targetPort||console.warn("Could not navigate to tunnel, as some provided information was not set.");let n=this._getTunnelAddress(t);switch(t.type){case"HTTPS":case"HTTP":null==(e=window.open(n))||e.focus();break;default:console.error("Unknown error when navigating to tunnel.")}}_getTunnelAddress(t){switch(t.type){case"HTTPS":case"HTTP":return"//"+t.id+"."+(t.hostname?t.hostname:window.location.hostname);case"TCP":return(t.hostname?t.hostname:window.location.hostname)+":"+t.assignedPort}}_isConfigComplete(t){return t.gatewayId?t.type?t.target?!!t.targetPort||(console.error("Could not start tunnel, since no gateway target port was configured."),!1):(console.error("Could not start tunnel, since no gateway target was configured."),!1):(console.error("Could not start tunnel, since no gateway type / protocol was configured."),!1):(console.error("Could not start tunnel, since no gateway asset was configured."),!1)}_getTunnelInfoByConfig(t){return{realm:r.displayRealm,gatewayId:t.gatewayId,type:t.type,target:t.target,targetPort:t.targetPort}}};__decorate([e()],GatewayWidget.prototype,"_loading",void 0),__decorate([e()],GatewayWidget.prototype,"_activeTunnel",void 0),__decorate([e()],GatewayWidget.prototype,"_isReady",void 0),GatewayWidget=GatewayWidget_1=__decorate([t("gateway-widget")],GatewayWidget);export{GatewayWidget};