import { h } from "@stencil/core";
import { propertySelectionToItems, itemsToPropertySelection, } from "../property-selection-format";
/**
 * Response Format Editor Component
 *
 * Allows users to select which properties should be returned in the query response.
 * Supports selecting properties on both the main limetype and related limetypes
 * through belongsto relations.
 *
 * Features:
 * - **Property selection**: Choose properties using dropdown navigation
 * - **Nested properties**: Select properties on related objects (e.g., company.name)
 * - **Property aliases**: Optionally rename properties in the response
 * - **Dynamic list**: Add/remove property selections
 * - **Real-time updates**: Changes immediately update the responseFormat
 *
 * The component generates a `ResponseFormat` object with the `object` field
 * containing the selected properties.
 *
 * @private
 */
export class ResponseFormatEditor {
    constructor() {
        /**
         * Optional label
         */
        this.label = 'Properties';
        this.items = [];
        this.handleItemChange = (index) => (event) => {
            event.stopPropagation();
            const newItems = [...this.items];
            if (event.detail === null) {
                // Remove item
                newItems.splice(index, 1);
            }
            else {
                // Update item
                newItems[index] = event.detail;
            }
            // Allow empty items - users can remove all properties
            this.items = newItems;
            this.emitChange();
        };
        this.handleAddProperty = () => {
            this.items = [...this.items, { path: '' }];
            this.emitChange();
        };
    }
    componentWillLoad() {
        if (!this.value) {
            // No value provided at all, use default _id
            this.items = [{ path: '_id' }];
            return;
        }
        if (this.isEmptyResponseFormat(this.value)) {
            // Show empty state for explicit empty objects
            this.items = [];
        }
        else if (this.value.object) {
            // Has object property with actual properties
            this.items = propertySelectionToItems(this.value.object);
        }
        else {
            // If value has aggregates but no object property, initialize items to empty array
            this.items = [];
        }
    }
    componentWillUpdate() {
        if (!this.value) {
            return;
        }
        if (this.value.object && !this.isEmptyResponseFormat(this.value)) {
            const currentItems = propertySelectionToItems(this.value.object);
            // Check if items have changed
            const itemsChanged = currentItems.length !== this.items.length ||
                !currentItems.every((item, index) => {
                    const current = this.items[index];
                    return (current &&
                        item.path === current.path &&
                        item.alias === current.alias &&
                        item.description === current.description);
                });
            if (itemsChanged) {
                this.items = currentItems;
            }
        }
        else {
            // Either empty response format or no object property - clear items
            if (this.items.length > 0) {
                this.items = [];
            }
        }
    }
    render() {
        if (!this.limetype) {
            return (h("div", { class: "empty-state" }, h("p", null, "Select a limetype to choose properties")));
        }
        // Render empty state when no properties are selected
        if (this.items.length === 0) {
            return (h("div", { class: "response-format-editor" }, h("h4", { class: "header" }, this.label), h("div", { class: "empty-state" }, h("p", { class: "empty-state-message" }, "No properties selected. The response will return empty objects."), h("limel-button", { label: "Add Property", icon: "plus_math", onClick: this.handleAddProperty }))));
        }
        return (h("div", { class: "response-format-editor" }, h("limel-header", { subheading: this.label }, this.renderPropertyCount()), h("div", { class: "property-list" }, this.items.map((item, index) => this.renderItem(item, index)), h("limel-button", { label: "Property", disabled: this.items.some((item) => !item.path || item.path.trim() === ''), icon: {
                name: 'plus_math',
                title: 'Add',
            }, onClick: this.handleAddProperty }))));
    }
    renderPropertyCount() {
        return [
            h("limel-badge", { slot: "actions", id: "counter-badge", label: this.items.length.toString() }),
            h("limel-tooltip", { elementId: "counter-badge", slot: "actions", label: "Number of selected properties" }),
        ];
    }
    renderItem(item, index) {
        return (h("limebb-lime-query-response-format-item", { key: `${item.path}-${index}`, class: "property-item", platform: this.platform, context: this.context, limetype: this.limetype, item: item, onItemChange: this.handleItemChange(index) }));
    }
    emitChange() {
        const propertySelection = itemsToPropertySelection(this.items);
        const responseFormat = {
            object: propertySelection,
        };
        this.change.emit(responseFormat);
    }
    /**
     * Check if the response format is empty
     *
     * A response format is considered empty in the following cases:
     * - Empty object: `{}`
     * - Object with empty object property and no aggregates: `{ object: {} }`
     *
     * Returns false for:
     * - `null` or `undefined`
     * - Objects with properties: `{ object: { _id: null } }`
     * - Objects with aggregates: `{ aggregates: {...} }`
     *
     * @param value - The ResponseFormat to check
     * @returns True if the response format is empty, false otherwise
     */
    isEmptyResponseFormat(value) {
        if (!value) {
            return false;
        }
        if (Object.keys(value).length === 0) {
            return true;
        }
        return !!(value.object &&
            Object.keys(value.object).length === 0 &&
            !value.aggregates);
    }
    static get is() { return "limebb-lime-query-response-format-editor"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["response-format-editor.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["response-format-editor.css"]
        };
    }
    static get properties() {
        return {
            "platform": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeWebComponentPlatform",
                    "resolved": "LimeWebComponentPlatform",
                    "references": {
                        "LimeWebComponentPlatform": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeWebComponentPlatform",
                            "referenceLocation": "LimeWebComponentPlatform"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Platform service provider"
                },
                "getter": false,
                "setter": false
            },
            "context": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeWebComponentContext",
                    "resolved": "LimeWebComponentContext",
                    "references": {
                        "LimeWebComponentContext": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeWebComponentContext",
                            "referenceLocation": "LimeWebComponentContext"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Component context"
                },
                "getter": false,
                "setter": false
            },
            "limetype": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The limetype to select properties from"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "limetype"
            },
            "value": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "ResponseFormat",
                    "resolved": "ResponseFormat",
                    "references": {
                        "ResponseFormat": {
                            "location": "import",
                            "path": "../lime-query.types",
                            "id": "src/components/lime-query-builder/lime-query.types.ts::ResponseFormat",
                            "referenceLocation": "ResponseFormat"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Current response format"
                },
                "getter": false,
                "setter": false
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Optional label"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label",
                "defaultValue": "'Properties'"
            }
        };
    }
    static get states() {
        return {
            "items": {}
        };
    }
    static get events() {
        return [{
                "method": "change",
                "name": "change",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the response format changes"
                },
                "complexType": {
                    "original": "ResponseFormat",
                    "resolved": "ResponseFormat",
                    "references": {
                        "ResponseFormat": {
                            "location": "import",
                            "path": "../lime-query.types",
                            "id": "src/components/lime-query-builder/lime-query.types.ts::ResponseFormat",
                            "referenceLocation": "ResponseFormat"
                        }
                    }
                }
            }];
    }
}
