import { h, Host } from "@stencil/core";
import { formatBytes } from "../../../util/format-bytes";
/**
 * Document item
 * Renders individual items of the document picker component.
 * @private
 */
export class DocumentItemComponent {
    constructor() {
        /**
         * The semantic role of the list item.
         * - 'radio': renders a radio button for single selection.
         * - 'checkbox': renders a checkbox for multiple selection.
         */
        this.type = 'checkbox';
        /**
         * The preferred file URL types to use when displaying
         * the document's image preview.
         */
        this.fileTypes = ['view', 'contents', 'download'];
        this.handleDocumentItemClick = (event) => {
            if (this.isUnavailable()) {
                return;
            }
            if ((event === null || event === void 0 ? void 0 : event.target) instanceof HTMLElement) {
                const isSelectionControl = event.target.closest('limel-checkbox') ||
                    event.target.closest('limel-radio-button');
                if (isSelectionControl) {
                    return;
                }
            }
            this.toggleSelection();
        };
        this.handleSelectionControlClick = (event) => {
            var _a, _b;
            event.stopPropagation();
            if (this.isUnavailable()) {
                return;
            }
            if (this.type === 'radio' && ((_a = this.item) === null || _a === void 0 ? void 0 : _a.selected)) {
                event.preventDefault();
                this.forceInputUnchecked(event);
                this.emitSelectionChange(!((_b = this.item) === null || _b === void 0 ? void 0 : _b.selected));
            }
        };
        this.handleSelectionControlChange = (event) => {
            var _a;
            event.stopPropagation();
            if (this.isUnavailable()) {
                return;
            }
            let isChecked;
            if ('detail' in event &&
                typeof event.detail === 'boolean') {
                isChecked = event.detail;
            }
            else {
                const input = event.target;
                isChecked = !!(input === null || input === void 0 ? void 0 : input.checked);
            }
            if (this.type === 'radio' && ((_a = this.item) === null || _a === void 0 ? void 0 : _a.selected) && !isChecked) {
                this.emitSelectionChange(false);
                return;
            }
            this.emitSelectionChange(isChecked);
        };
        this.handleKeyDown = (event) => {
            if (event.key !== ' ' && event.key !== 'Enter') {
                return;
            }
            event.preventDefault();
            if (this.isUnavailable()) {
                return;
            }
            this.toggleSelection();
        };
    }
    render() {
        const isUnavailable = this.isUnavailable();
        const image = this.getImage();
        return (h(Host, { key: '4e7f632c97cd078ee44cc262b3531b87409344fb', id: String(this.item.file.id), class: {
                'has-image': !!image,
                'has-error': !!this.item.hasError,
            }, role: this.type === 'radio' ? 'radio' : 'checkbox', "aria-checked": this.item.selected ? 'true' : 'false', "aria-disabled": isUnavailable ? 'true' : 'false', tabIndex: isUnavailable ? -1 : 0 }, h("limel-card", { key: 'b560d107ba3bfee84158b2867fb594eb698072c3', image: image, clickable: isUnavailable ? false : true, onClick: this.handleDocumentItemClick, onKeyDown: this.handleKeyDown }, h("div", { key: '798a25ef8ef4ca1470a91afaaf2fc3e975473368', slot: "component" }, this.renderFileSize(), this.renderBooleanInput())), this.renderHelp()));
    }
    renderBooleanInput() {
        const id = this.getControlId();
        if (this.type === 'radio') {
            return (h("limel-radio-button", { id: id, label: this.item.file.filename, disabled: this.isUnavailable(), checked: this.item.selected, onClick: this.handleSelectionControlClick, onChange: this.handleSelectionControlChange }));
        }
        return (h("limel-checkbox", { id: id, label: this.item.file.filename, disabled: this.isUnavailable(), checked: this.item.selected, onClick: this.handleSelectionControlClick, onChange: this.handleSelectionControlChange }));
    }
    renderFileSize() {
        var _a, _b;
        const formattedFileSize = formatBytes((_b = (_a = this.item) === null || _a === void 0 ? void 0 : _a.file) === null || _b === void 0 ? void 0 : _b.size);
        if (!formattedFileSize) {
            return;
        }
        return h("span", { class: "file-size" }, formattedFileSize);
    }
    renderHelp() {
        if (!this.item.help) {
            return;
        }
        return h("limel-help", { value: this.item.help, openDirection: "bottom-end" });
    }
    toggleSelection() {
        var _a, _b;
        if (this.type === 'radio') {
            const nextSelectedState = !((_a = this.item) === null || _a === void 0 ? void 0 : _a.selected);
            this.emitSelectionChange(nextSelectedState);
            return;
        }
        const nextSelectedState = !((_b = this.item) === null || _b === void 0 ? void 0 : _b.selected);
        this.emitSelectionChange(nextSelectedState);
    }
    emitSelectionChange(selected) {
        this.interact.emit(Object.assign(Object.assign({}, this.item), { selected }));
    }
    getControlId() {
        return `boolean-input-${String(this.item.file.id)}`;
    }
    isUnavailable() {
        var _a, _b;
        return ((_a = this.item) === null || _a === void 0 ? void 0 : _a.disabled) || ((_b = this.item) === null || _b === void 0 ? void 0 : _b.hasError);
    }
    forceInputUnchecked(event) {
        const target = event.target;
        const host = target === null || target === void 0 ? void 0 : target.closest('limel-radio-button');
        const input = host === null || host === void 0 ? void 0 : host.querySelector('input[type="radio"]');
        if (input) {
            input.checked = false;
        }
    }
    getImage() {
        const href = this.hrefForFile();
        if (!href) {
            return;
        }
        return {
            src: href,
            alt: this.item.file.filename,
        };
    }
    hrefForFile() {
        return ['preview', ...this.fileTypes]
            .map((type) => this.item.file.getUrl(type))
            .find(Boolean);
    }
    static get is() { return "limebb-document-item"; }
    static get encapsulation() { return "shadow"; }
    static get delegatesFocus() { return true; }
    static get originalStyleUrls() {
        return {
            "$": ["document-item.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["document-item.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": true,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "inheritdoc",
                            "text": undefined
                        }],
                    "text": "Reference to the platform service container.\n\nUse this to access all platform services like repositories, HTTP client,\ncommand bus, navigator, and more. The platform instance is shared across\nall components in the same application context."
                },
                "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": [{
                            "name": "inheritdoc",
                            "text": undefined
                        }],
                    "text": "The context describing where this component is running.\n\nThe context provides information about the current limetype and record ID\n(if viewing/editing a specific record). Components can use this to load\nrelevant data and understand their operating environment."
                },
                "getter": false,
                "setter": false
            },
            "item": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "DocumentItem",
                    "resolved": "DocumentItem",
                    "references": {
                        "DocumentItem": {
                            "location": "import",
                            "path": "./document-item.types",
                            "id": "src/components/document-picker/document-item/document-item.types.ts::DocumentItem",
                            "referenceLocation": "DocumentItem"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The item to display in the document picker."
                },
                "getter": false,
                "setter": false
            },
            "type": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'radio' | 'checkbox'",
                    "resolved": "\"checkbox\" | \"radio\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The semantic role of the list item.\n- 'radio': renders a radio button for single selection.\n- 'checkbox': renders a checkbox for multiple selection."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "type",
                "defaultValue": "'checkbox'"
            },
            "fileTypes": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "LimeFileUrlType[]",
                    "resolved": "LimeFileUrlType[]",
                    "references": {
                        "LimeFileUrlType": {
                            "location": "import",
                            "path": "@limetech/lime-web-components",
                            "id": "node_modules::LimeFileUrlType",
                            "referenceLocation": "LimeFileUrlType"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The preferred file URL types to use when displaying\nthe document's image preview."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "['view', 'contents', 'download']"
            }
        };
    }
    static get events() {
        return [{
                "method": "interact",
                "name": "interact",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Fired when clicking on the document item."
                },
                "complexType": {
                    "original": "DocumentItem",
                    "resolved": "DocumentItem",
                    "references": {
                        "DocumentItem": {
                            "location": "import",
                            "path": "./document-item.types",
                            "id": "src/components/document-picker/document-item/document-item.types.ts::DocumentItem",
                            "referenceLocation": "DocumentItem"
                        }
                    }
                }
            }];
    }
}
