import { Host, h } from "@stencil/core";
import { getStore } from "../../store";
import { watchStoreLocale } from "../../utils/locale-state";
import { getStoreUnavailableError } from "../../utils/store-error";
export class LsStatus {
    constructor() {
        /**
         * Specifies the IDs of the sensors that are to be displayed.
         */
        this.sensorIds = "500,501,502,503,514,515,590";
        /**
         * Selects which label set to use for status items.
         */
        this.labelType = "default";
        /**
         * The sensor IDs input property, converted to an array of numbers.
         */
        this.sensorIdsArray = this.sensorIds
            .split(",")
            .filter((id) => id.trim() !== "")
            .map((id) => parseInt(id.trim(), 10));
        /**
         * Centralized error state for tracking component errors
         */
        this.errorState = {
            hasError: false,
            messageKey: undefined,
            type: "",
        };
        this.useTwoColumns = false;
        this.storeUnsubscribe = null;
        this.resizeObserver = null;
        this.filterBackdoorSensor = (hasBackDoor) => {
            if (hasBackDoor)
                return;
            this.sensorIdsArray = this.sensorIdsArray.filter((sensor) => {
                return sensor !== 503;
            });
        };
    }
    async componentWillLoad() {
        this.store = await getStore(this.idKey);
        watchStoreLocale(this, this.store);
        this.filterBackdoorSensor(this.store.state.hasBackDoor);
        this.updateErrorState();
        if (this.store !== null) {
            this.storeUnsubscribe = this.store.onChange("error", () => {
                this.updateErrorState();
            });
        }
    }
    componentDidLoad() {
        // Initialize and keep the column layout in sync with host size changes.
        this.updateColumnLayout();
        if (typeof ResizeObserver === "undefined")
            return;
        this.resizeObserver = new ResizeObserver(() => {
            this.updateColumnLayout();
        });
        this.resizeObserver.observe(this.hostEl);
    }
    disconnectedCallback() {
        if (this.storeUnsubscribe !== null) {
            this.storeUnsubscribe();
            this.storeUnsubscribe = null;
        }
        if (this.resizeObserver !== null) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
        }
    }
    /**
     * Updates the error state based on current component conditions
     */
    updateErrorState() {
        var _a;
        if (this.store === null) {
            this.errorState = getStoreUnavailableError((_a = this.store) === null || _a === void 0 ? void 0 : _a.state.locale);
            return;
        }
        if (this.store.state.error.hasError) {
            this.errorState = {
                hasError: true,
                messageKey: this.store.state.error.messageKey,
                type: this.store.state.error.type,
            };
            return;
        }
        this.errorState = {
            hasError: false,
            messageKey: undefined,
            type: "",
        };
    }
    parseLengthToPx(value) {
        // Support only px/em/rem values for the grid breakpoint.
        if (value.trim() === "")
            return null;
        const numeric = parseFloat(value);
        if (Number.isNaN(numeric) || numeric < 0)
            return null;
        if (value.endsWith("px")) {
            return numeric;
        }
        if (value.endsWith("rem")) {
            const rootFontSizeValue = getComputedStyle(document.documentElement).fontSize;
            const rootFontSize = parseFloat(rootFontSizeValue);
            return (numeric *
                (Number.isNaN(rootFontSize)
                    ? LsStatus.DEFAULT_FONT_SIZE_PX
                    : rootFontSize));
        }
        if (value.endsWith("em")) {
            const hostFontSizeValue = getComputedStyle(this.hostEl).fontSize;
            const hostFontSize = parseFloat(hostFontSizeValue);
            return (numeric *
                (Number.isNaN(hostFontSize)
                    ? LsStatus.DEFAULT_FONT_SIZE_PX
                    : hostFontSize));
        }
        return null;
    }
    getErrorMessageForDisplay() {
        var _a;
        const errorKey = (_a = this.errorState.messageKey) !== null && _a !== void 0 ? _a : "CONSOLE_INFO";
        return this.store.t(`errors:${errorKey}`);
    }
    updateColumnLayout() {
        // Toggle two-column layout when the host width meets the breakpoint.
        if (this.hostEl === null)
            return;
        const computedStyles = getComputedStyle(this.hostEl);
        const breakpointValue = computedStyles
            .getPropertyValue("--ls-status-grid-breakpoint")
            .trim();
        const breakpointPx = this.parseLengthToPx(breakpointValue);
        if (breakpointPx === null) {
            this.useTwoColumns = false;
            return;
        }
        const width = this.hostEl.getBoundingClientRect().width;
        const shouldUseTwoColumns = width >= breakpointPx;
        if (this.useTwoColumns !== shouldUseTwoColumns) {
            this.useTwoColumns = shouldUseTwoColumns;
        }
    }
    render() {
        const contentClass = {
            content: true,
            "two-columns": this.useTwoColumns,
            blur: this.errorState.hasError,
        };
        return (h(Host, { key: 'ccfa629f5672b20ad2b17ce8f9c2e9d451d40a68' }, h("slot", { key: '30465accd67a299ecaa16408b99b282fb99e40f4' }), h("div", { key: '478f6ab82abbf8c2cccd4a6b58f6fd57dbcd2585', class: contentClass }, this.sensorIdsArray.map((sensor) => (h("ls-status-item", { "sensor-id": sensor, "id-key": this.idKey, "label-type": this.labelType })))), this.errorState.hasError && (h("div", { key: '868e594d71757a31a187a8e63e5b265df13f7c4c', class: "error-message" }, this.getErrorMessageForDisplay()))));
    }
    static get is() { return "ls-status"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ls-status.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ls-status.css"]
        };
    }
    static get properties() {
        return {
            "sensorIds": {
                "type": "string",
                "attribute": "sensor-ids",
                "mutable": false,
                "complexType": {
                    "original": "\"500,501,502,503,514,515,590\"",
                    "resolved": "\"500,501,502,503,514,515,590\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Specifies the IDs of the sensors that are to be displayed."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "\"500,501,502,503,514,515,590\""
            },
            "idKey": {
                "type": "string",
                "attribute": "id-key",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The unique key that is used to identify store data."
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "labelType": {
                "type": "string",
                "attribute": "label-type",
                "mutable": false,
                "complexType": {
                    "original": "\"default\" | \"short\"",
                    "resolved": "\"default\" | \"short\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Selects which label set to use for status items."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "\"default\""
            }
        };
    }
    static get states() {
        return {
            "sensorIdsArray": {},
            "errorState": {},
            "useTwoColumns": {}
        };
    }
    static get elementRef() { return "hostEl"; }
}
LsStatus.DEFAULT_FONT_SIZE_PX = 16;
//# sourceMappingURL=ls-status.js.map
