var __decorate=this&&this.__decorate||function(t,e,i,a){var n,o=arguments.length,l=o<3?e:null===a?a=Object.getOwnPropertyDescriptor(e,i):a;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)l=Reflect.decorate(t,e,i,a);else for(var r=t.length-1;r>=0;r--)(n=t[r])&&(l=(o<3?n(l):o>3?n(e,i,l):n(e,i))||l);return o>3&&l&&Object.defineProperty(e,i,l),l};import{css as t,html as e}from"lit";import{customElement as i,query as a}from"lit/decorators.js";import{WidgetSettings as n}from"../util/widget-settings";import"../panels/attributes-chart-panel";import"../util/settings-panel";import{i18next as o}from"@openremote/or-translate";import l from"lodash.debounce";import{InputType as r}from"@openremote/or-mwc-components/or-mwc-input";import{when as s}from"lit/directives/when.js";import{OrChart as d}from"@openremote/or-chart";import{getAssetDescriptorIconTemplate as u}from"@openremote/or-icon";let styling=t`
  .switch-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
`,ChartSettings=class extends n{constructor(){super(...arguments),this.timeWindowOptions=new Map,this.timePrefixOptions=[],this.samplingOptions=new Map}setTimeWindowOptions(t){this.timeWindowOptions=t}setTimePrefixOptions(t){this.timePrefixOptions=t}setSamplingOptions(t){this.samplingOptions=t}static get styles(){return[...super.styles,styling]}render(){var t,i,a,n,l,g,p,m,h,v,f;let c=this.widgetConfig.attributeConfig,b=null==(a=null==(i=null==(t=this.widgetConfig.chartOptions.options)?void 0:t.scales)?void 0:i.y)?void 0:a.min,w=null==(g=null==(l=null==(n=this.widgetConfig.chartOptions.options)?void 0:n.scales)?void 0:l.y)?void 0:g.max,C=((null==(p=null==c?void 0:c.rightAxisAttributes)?void 0:p.length)||0)>0,y=(t,i,a)=>{var n,o,l,r,s,g;let p=null==(l=null==(o=null==(n=this.widgetConfig.attributeColors)?void 0:n.find(e=>e[0].id===t.id&&e[0].name===i.name))?void 0:o[1])?void 0:l.replace("#","");if(!p){let e=null==(r=this.widgetConfig.attributeRefs)?void 0:r.findIndex(e=>e.id===t.id&&e.name===i.name);e>=0&&(p=null==(g=null==(s=d.DEFAULT_COLORS)?void 0:s[e%d.DEFAULT_COLORS.length])?void 0:g.replace("#",""))}return e`<span>${u(a,void 0,void 0,p)}</span>`},x=t=>{var e,i,a,n,l,r,s,u,g,p,m,h,v,f;let b=(null==(a=null==(i=null==(e=this.widgetConfig)?void 0:e.attributeConfig)?void 0:i.rightAxisAttributes)?void 0:a.find(e=>e.id===t.id&&e.name===t.name))!==void 0,w=(null==(n=null==c?void 0:c.faintAttributes)?void 0:n.find(e=>e.id===t.id&&e.name===t.name))!==void 0,C=(null==(l=null==c?void 0:c.smoothAttributes)?void 0:l.find(e=>e.id===t.id&&e.name===t.name))!==void 0,y=(null==(r=null==c?void 0:c.steppedAttributes)?void 0:r.find(e=>e.id===t.id&&e.name===t.name))!==void 0,x=(null==(s=null==c?void 0:c.areaAttributes)?void 0:s.find(e=>e.id===t.id&&e.name===t.name))!==void 0,A=(null==(u=null==c?void 0:c.extendedAttributes)?void 0:u.find(e=>e.id===t.id&&e.name===t.name))!==void 0,$=null==(m=null==(p=null==(g=this.widgetConfig)?void 0:g.attributeColors)?void 0:p.find(e=>e[0].id===t.id&&e[0].name===t.name))?void 0:m[1],T=!1;if($)T=!0;else{let e=null==(v=null==(h=this.widgetConfig)?void 0:h.attributeRefs)?void 0:v.findIndex(e=>e.id===t.id&&e.name===t.name);e>=0&&($=null==(f=d.DEFAULT_COLORS)?void 0:f[e%d.DEFAULT_COLORS.length])}return[{icon:"palette",tooltip:o.t("dashboard.lineColor"),active:T,color:$,disabled:!1},{icon:"chart-bell-curve-cumulative",tooltip:o.t("dashboard.smooth"),active:C,color:$,disabled:!1},{icon:"square-wave",tooltip:o.t("dashboard.stepped"),active:y,color:$,disabled:!1},{icon:"chart-areaspline-variant",tooltip:o.t("dashboard.fill"),active:x,color:$,disabled:!1},{icon:"arrange-send-backward",tooltip:o.t("dashboard.faint"),active:w,color:$,disabled:!1},{icon:"arrow-expand-right",tooltip:o.t("dashboard.extendData"),active:A,color:$,disabled:!1},{icon:b?"arrow-right-bold":"arrow-left-bold",tooltip:o.t("dashboard.toggleAxis"),active:b,color:$,disabled:!1}]},A=null!=(m=this.timePrefixOptions.find(t=>{var e,i;return null==(i=null==(e=this.widgetConfig)?void 0:e.defaultTimePresetKey)?void 0:i.startsWith(t)}))?m:this.timePrefixOptions[0],[$,T]=null==(v=null==(h=this.widgetConfig)?void 0:h.defaultTimePresetKey)?void 0:v.split(A);T&&this.timeWindowOptions.has(T)||(T=Array.from(this.timeWindowOptions.keys())[0]);let S=this.timePrefixOptions.map(t=>({value:t,label:o.t(t.toLowerCase())})),O=Array.from(this.timeWindowOptions.keys()).map(t=>({value:t,label:o.t(t.toLowerCase())}));return e`
            <div>
                <!-- Attribute selection -->
                <settings-panel displayName="attributes" expanded>
                    <attributes-chart-panel .attributeRefs="${this.widgetConfig.attributeRefs}" multi onlyDataAttrs includePredictedDataAttrs .attributeFilter="${t=>["boolean","positiveInteger","positiveNumber","number","long","integer","bigInteger","negativeInteger","negativeNumber","bigNumber","integerByte","direction"].includes(t.type)}" style="padding-bottom: 12px;"
                                      .attributeIconCallback="${y}" .attributeActionCallback="${x}"
                                      @attribute-action="${t=>this.onAttributeAction(t)}"
                                      @attribute-replace="${t=>this.onAttributeReplace(t)}"
                                      @attribute-select="${t=>this.onAttributesSelect(t)}"
                    ></attributes-chart-panel>
                </settings-panel>

                <!-- Time options -->
                <settings-panel displayName="time" expanded>
                    <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 6px;">
                        <!-- This/last selection of timeframe -->
                        <or-vaadin-select .items=${S} value=${A} @change=${t=>this.onTimePrefixSelect(t)}>
                            <or-translate slot="label" value="prefixDefault"></or-translate>
                        </or-vaadin-select>
                        <!-- Select time frame -->
                        <or-vaadin-select .items=${O} .value=${T} @change=${t=>this.onTimeWindowSelect(t)}>
                            <or-translate slot="label" value="timeframeDefault"></or-translate>
                        </or-vaadin-select>
                    </div>  
                </settings-panel>
                <!-- Display options --> 
                <settings-panel displayName="display" expanded>
                    <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 6px;">
                        <div class="switch-container">
                            <span><or-translate value="dashboard.toggleStackView"></or-translate></span>
                            <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.stacked}"
                                          @or-mwc-input-changed="${t=>this.onStackViewToggle(t)}"
                            ></or-mwc-input>
                        </div>
                        <div class="switch-container">
                            <span><or-translate value="dashboard.allowTimerangeSelect"></or-translate></span>
                            <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px;" .value="${!this.widgetConfig.showTimestampControls}"
                                          @or-mwc-input-changed="${t=>this.onTimestampControlsToggle(t)}"
                            ></or-mwc-input>
                        </div>
                        <div class="switch-container">
                            <span><or-translate value="dashboard.showLegend"></or-translate></span>
                            <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showLegend}"
                                          @or-mwc-input-changed="${t=>this.onShowLegendToggle(t)}"
                            ></or-mwc-input>
                        </div>
                        <!-- Datazoombar -->
                        <div class="switch-container">
                            <span><or-translate value="dashboard.showZoomBar"></or-translate></span>
                            <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showZoomBar}"
                                          @or-mwc-input-changed="${t=>this.onShowZoomBarToggle(t)}"
                            ></or-mwc-input>
                        </div>
                    </div>
                </settings-panel>

                <!-- Axis configuration -->
                <settings-panel displayName="dashboard.axisConfig" expanded>
                    <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 16px;">
                        <!-- Left axis configuration -->
                        <div>
                            ${s(C,()=>e`
                                <div style="margin-bottom: 8px;">
                                    <span><or-translate value="dashboard.leftAxis"></or-translate></span>
                                </div>
                            `)}
                            <div style="display: flex; align-items: baseline;">
                                ${void 0!==w?e`
                                    <or-vaadin-number-field value=${w} @change=${t=>this.onMinMaxValueChange("left","max",t)}>
                                        <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="max"></or-translate></span>
                                    </or-vaadin-number-field>
                                `:e`
                                    <or-vaadin-text-field value="auto" readonly>
                                        <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="max"></or-translate></span>
                                    </or-vaadin-text-field>
                                `}
                                <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px 0 0;" .value="${void 0!==w}"
                                              @or-mwc-input-changed="${t=>this.onMinMaxValueToggle("left","max",t)}"
                                ></or-mwc-input>
                            </div>
                            <div style="display: flex; margin-top: 12px;">
                                ${void 0!==b?e`
                                    <or-vaadin-number-field value=${b} @change=${t=>this.onMinMaxValueChange("left","min",t)}>
                                        <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="min"></or-translate></span>
                                    </or-vaadin-number-field>
                                `:e`
                                    <or-vaadin-text-field value="auto" readonly>
                                        <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="min"></or-translate></span>
                                    </or-vaadin-text-field>
                                `}
                                <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px 0 0;" .value="${void 0!==b}"
                                              @or-mwc-input-changed="${t=>this.onMinMaxValueToggle("left","min",t)}"
                                ></or-mwc-input>
                            </div>
                        </div>

                        <!-- Right axis configuration -->
                        ${s(C,()=>{var t,i,a,n,o,l;let s=null==(a=null==(i=null==(t=this.widgetConfig.chartOptions.options)?void 0:t.scales)?void 0:i.y1)?void 0:a.min,d=null==(l=null==(o=null==(n=this.widgetConfig.chartOptions.options)?void 0:n.scales)?void 0:o.y1)?void 0:l.max;return e`
                                <div>
                                    <div style="margin-bottom: 8px;">
                                        <span><or-translate value="dashboard.rightAxis"></or-translate></span>
                                    </div>
                                    <div style="display: flex;">
                                        ${void 0!==d?e`
                                            <or-vaadin-number-field value=${d} @change=${t=>this.onMinMaxValueChange("right","max",t)}>
                                                <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="max"></or-translate></span>
                                            </or-vaadin-number-field>
                                        `:e`
                                            <or-vaadin-text-field value="auto" readonly>
                                                <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="max"></or-translate></span>
                                            </or-vaadin-text-field>
                                        `}
                                        <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px 0 0;" .value="${void 0!==d}"
                                                      @or-mwc-input-changed="${t=>this.onMinMaxValueToggle("right","max",t)}"
                                        ></or-mwc-input>
                                    </div>
                                    <div style="display: flex; margin-top: 12px; align-items: baseline;">
                                        ${void 0!==s?e`
                                            <or-vaadin-number-field value=${s} @change=${t=>this.onMinMaxValueChange("right","min",t)}>
                                                <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="min"></or-translate></span>
                                            </or-vaadin-number-field>
                                        `:e`
                                            <or-vaadin-text-field value="auto" readonly>
                                                <span slot="label"><or-translate value="yAxis"></or-translate> <or-translate value="min"></or-translate></span>
                                            </or-vaadin-text-field>
                                        `}
                                        <or-mwc-input .type="${r.SWITCH}" style="margin: 0 -10px 0 0;" .value="${void 0!==s}"
                                                      @or-mwc-input-changed="${t=>this.onMinMaxValueToggle("right","min",t)}"
                                        ></or-mwc-input>
                                    </div>
                                </div>
                            `})}
                    </div>
                </settings-panel>

                <!-- Data sampling options -->
                ${s(Array.from(null==(f=this.samplingOptions)?void 0:f.keys()).length>1,()=>{let t=Array.from(this.samplingOptions.entries()).map(t=>({value:t[0],label:o.t(t[1])})),i=this.widgetConfig.datapointQuery.type;return e`
                        <settings-panel displayName="dataSampling" expanded="${!1}">
                            <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 12px;">
                                <div>
                                    <or-vaadin-select .items=${t} value=${i} @change=${t=>this.onSamplingQueryChange(t)}>
                                        <or-translate slot="label" value="algorithm"></or-translate>
                                    </or-vaadin-select>
                                </div>
                                <div>
                                    ${this.getSamplingOptionsTemplate(this.widgetConfig.datapointQuery.type)}
                                </div>
                            </div>
                        </settings-panel>
                    `})}
            </div>
        `}getSamplingOptionsTemplate(t){if("interval"!==t)return e``;{let t=this.widgetConfig.datapointQuery,i=["AVG","MIN","MAX"].map(t=>({value:t,label:o.t(t)}));return e`
                    <or-vaadin-select .items=${i} value=${t.formula} required @change=${e=>{t.formula=e.currentTarget.value,this.notifyConfigUpdate()}}>
                        <or-translate slot="label" value="algorithmMethod"></or-translate>
                    </or-vaadin-select>
                `}}onAttributeAction(t){let{attributeRef:e,action:i}=t.detail;switch(i.icon){case"palette":this.openColorPickDialog(e);break;case"arrow-right-bold":case"arrow-left-bold":this._toggleAttributeSetting("rightAxisAttributes",e);break;case"chart-bell-curve-cumulative":i.active||this._removeAttributeSetting("steppedAttributes",e),this._toggleAttributeSetting("smoothAttributes",e);break;case"square-wave":i.active||this._removeAttributeSetting("smoothAttributes",e),this._toggleAttributeSetting("steppedAttributes",e);break;case"chart-areaspline-variant":this._toggleAttributeSetting("areaAttributes",e);break;case"arrange-send-backward":this._toggleAttributeSetting("faintAttributes",e);break;case"arrow-expand-right":this._toggleAttributeSetting("extendedAttributes",e);break;default:console.warn("Unknown attribute panel action:",i)}}onAttributesSelect(t){this.widgetConfig.attributeRefs.filter(e=>!t.detail.attributeRefs.some(t=>t.id===e.id&&t.name===e.name)).forEach(t=>{this.removeFromAttributeConfig(t),this.removeFromAttributeColors(t)}),this.widgetConfig.attributeRefs=t.detail.attributeRefs,this.notifyConfigUpdate()}onAttributeReplace(t){var e;let{oldRef:i,newRef:a}=t.detail,n=t=>t.id===i.id&&t.name===i.name,o=this.widgetConfig.attributeConfig;o&&Object.keys(o).forEach(t=>{var e;o[t]=null==(e=o[t])?void 0:e.map(t=>n(t)?{id:a.id,name:a.name}:t)}),this.widgetConfig.attributeColors=(null!=(e=this.widgetConfig.attributeColors)?e:[]).map(t=>n(t[0])?[{id:a.id,name:a.name},t[1]]:t);let l=this.widgetConfig.attributeRefs.findIndex(n);l>=0&&(this.widgetConfig.attributeRefs[l]={id:a.id,name:a.name}),this.notifyConfigUpdate()}removeFromAttributeConfig(t){let e=this.widgetConfig.attributeConfig;e&&Object.keys(e).forEach(i=>{var a;e[i]=null==(a=e[i])?void 0:a.filter(e=>e.id!==t.id||e.name!==t.name)})}_toggleAttributeSetting(t,e){var i;let a=null==(i=this.widgetConfig.attributeConfig)?void 0:i[t],n=null==a?void 0:a.findIndex(t=>t.id===e.id&&t.name===e.name);null==n||n<0?this._addAttributeSetting(t,e):this._removeAttributeSetting(t,e),this.notifyConfigUpdate()}_addAttributeSetting(t,e){var i,a;null!=(i=this.widgetConfig).attributeConfig||(i.attributeConfig={}),null!=(a=this.widgetConfig.attributeConfig)[t]||(a[t]=[]);let n=this.widgetConfig.attributeConfig[t];n.find(t=>t.id===e.id&&t.name===e.name)?console.warn(`Could not add attribute ${e.name}; attribute already exists in attribute setting ${t}.`,n):(console.debug(`Adding attribute ${e.name} to setting ${t} in widget config.`),n.push(e))}_removeAttributeSetting(t,e){var i;let a=null==(i=this.widgetConfig.attributeConfig)?void 0:i[t];if(!a)return void console.warn(`Could not remove attribute; attribute setting ${t} not found in widget config.`,a);let n=null==a?void 0:a.findIndex(t=>t.id===e.id&&t.name===e.name);null==n||n<0?console.warn(`Could not remove attribute; attribute ${e.name} not found in attribute setting ${t}.`,a):(console.debug(`Removing attribute ${e.name} from setting ${t} in widget config.`),1===a.length?delete this.widgetConfig.attributeConfig[t]:a.splice(n,1))}removeFromAttributeColors(t){this.widgetConfig.attributeColors=this.widgetConfig.attributeColors.filter(([e,i])=>e.id!==t.id||e.name!==t.name)}openColorPickDialog(t){var e,i;let a=null==(i=null==(e=this._attributesPanelElem)?void 0:e.shadowRoot)?void 0:i.querySelector(`#chart-color-${t.id}-${t.name}`);a&&(a.addEventListener("input",l(()=>{var e;let i=a.value;null!=(e=this.widgetConfig).attributeColors||(e.attributeColors=[]);let n=this.widgetConfig.attributeColors.find(e=>e[0].id===t.id&&e[0].name===t.name);n?n[1]=i:this.widgetConfig.attributeColors.push([t,i]),this.widgetConfig.attributeColors=[...this.widgetConfig.attributeColors],this.notifyConfigUpdate()},200)),a.click())}onTimePrefixSelect(t){let e=this.widgetConfig.defaultTimePresetKey,i=t.currentTarget.value,a=this.timePrefixOptions;a.find(t=>e.includes(t))?a.forEach(t=>e=e.replace(t,"")):e=Array.from(this.timeWindowOptions.keys())[0],this.widgetConfig.defaultTimePresetKey=i+e,console.debug(`Updated default time preset to ${this.widgetConfig.defaultTimePresetKey}`),this.notifyConfigUpdate()}onTimeWindowSelect(t){let e=this.widgetConfig.defaultTimePresetKey,i=t.currentTarget.value,a=Array.from(this.timeWindowOptions.keys()).sort((t,e)=>e.length-t.length);a.find(t=>e.includes(t))?a.forEach(t=>e=e.replace(t,"")):e=this.timePrefixOptions[0],this.widgetConfig.defaultTimePresetKey=e+i,console.debug(`Updated default time preset to ${this.widgetConfig.defaultTimePresetKey}`),this.notifyConfigUpdate()}onStackViewToggle(t){this.widgetConfig.stacked=t.detail.value,this.notifyConfigUpdate()}onTimestampControlsToggle(t){this.widgetConfig.showTimestampControls=!t.detail.value,this.notifyConfigUpdate()}onShowLegendToggle(t){this.widgetConfig.showLegend=t.detail.value,this.notifyConfigUpdate()}onShowZoomBarToggle(t){this.widgetConfig.showZoomBar=t.detail.value,this.notifyConfigUpdate()}setAxisMinMaxValue(t,e,i){"left"===t?"min"===e?this.widgetConfig.chartOptions.options.scales.y.min=i:this.widgetConfig.chartOptions.options.scales.y.max=i:"min"===e?this.widgetConfig.chartOptions.options.scales.y1.min=i:this.widgetConfig.chartOptions.options.scales.y1.max=i,this.notifyConfigUpdate()}onMinMaxValueChange(t,e,i){let a=i.currentTarget;a.checkValidity()&&this.setAxisMinMaxValue(t,e,Number(a.value))}onMinMaxValueToggle(t,e,i){this.setAxisMinMaxValue(t,e,i.detail.value?100*("min"!==e):void 0)}onSamplingQueryChange(t){let e=t.currentTarget;this.widgetConfig.datapointQuery.type=e.value,this.notifyConfigUpdate()}};__decorate([a("attributes-chart-panel")],ChartSettings.prototype,"_attributesPanelElem",void 0),ChartSettings=__decorate([i("chart-settings")],ChartSettings);export{ChartSettings};