'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-457520a1.js');

var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, privateMap) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to get private field on non-instance");
    }
    return privateMap.get(receiver);
};
var _server;
const OptionCreator = class {
    constructor(hostRef) {
        index$1.registerInstance(this, hostRef);
        this.value = [];
        _server.set(this, window.BCE.file);
        this.handleInput = (event, index) => {
            const input = event.target;
            if (!input)
                return;
            // Update value
            const copy = [...this.value];
            const update = Object.assign(Object.assign({}, this.value[index]), { text: input.value });
            copy.splice(index, 1, update);
            this.updateValue(copy);
            event.stopPropagation();
        };
        this.handleKeyDown = async (event, index) => {
            switch (event.keyCode) {
                case 8: // Backspace
                    const target = event.target;
                    if (!target.value && index != 0) {
                        this.focusOption(index - 1);
                        this.handleRemove(index);
                    }
                    return;
                case 13: //Enter
                    return this.addOption();
            }
        };
        this.handleOther = () => {
            this.other = !this.other;
            this.value = this.other
                ? [...this.value, { text: this.label.labelOCOther || '' }]
                : this.value.slice(0, -1);
            this.onOther.emit(this.other);
        };
        this.handleRemove = (index) => {
            const copy = [...this.value];
            copy.splice(index, 1);
            this.updateValue(copy);
        };
        this.handleColor = (index) => { };
        this.handleImage = (index) => {
            const current = this.value[index];
            if ('image' in current && current.image)
                this.deleteImage(current, index);
            else
                this.uploadImage(index);
        };
        this.onOther = index$1.createEvent(this, "other", 7);
    }
    watchValue(value) {
        if (!value.length)
            this.addOption(false);
    }
    async addOption(focus = true) {
        const insert = { text: '' };
        const value = this.other
            ? [...this.value.slice(0, -1), insert, ...this.value.slice(-1)]
            : [...this.value, insert];
        this.updateValue(value);
        if (focus)
            this.focusLast(true);
    }
    async focusLast(nextTick) {
        return this.focusOption(-(this.other ? 2 : 1), nextTick);
    }
    async focusOption(index, nextTick = false) {
        if (nextTick)
            await new Promise(res => setTimeout(res, 100));
        // Find last input element
        const query = '[data-option] bce-input';
        const options = this.el.shadowRoot.querySelectorAll(query);
        const option = options[index < 0 ? options.length + index : index];
        const input = option && option.shadowRoot.querySelector('input');
        // Set focus to new element
        if (input)
            input.focus();
    }
    async uploadImage(index) {
        const root = document.querySelector('bce-root');
        // Create upload dialog
        const upload = document.createElement('bce-upload');
        upload.accept = 'image/*';
        upload.active = true;
        upload.dialog = true;
        // Trigger upload
        const file = await root.execute(upload, res => {
            upload.addEventListener('input', event => {
                const target = event.target;
                res(target.value[0]);
            });
        }, { display: true });
        // Update value
        const copy = [...this.value];
        copy.splice(index, 1, Object.assign(Object.assign({}, this.value[index]), { image: file }));
        // Emit value
        console.log(copy);
    }
    deleteImage(option, index) {
        if (!('image' in option) || !option.image)
            return;
        __classPrivateFieldGet(this, _server).delete(option.image, {});
        // Update value
        const copy = [...this.value];
        const value = Object.assign({}, this.value[index]);
        if ('image' in value)
            delete value.image;
        copy.splice(index, 1, value);
        this.updateValue(copy);
    }
    updateValue(value) {
        this.value = value;
        const e = new globalThis.Event('input', { bubbles: true, composed: true });
        this.el.dispatchEvent(e);
    }
    componentWillLoad() {
        this.watchValue(this.value);
    }
    renderTooltip(icon, content) {
        if (!content)
            return null;
        return (index$1.h("bce-tooltip", { placement: "left", icon: icon }, content));
    }
    renderMetadata(option) {
        if (!('image' in option))
            return;
        return index$1.h("div", { "data-meta": true }, this.renderTooltip('fas:image', option.image));
    }
    renderOption(option, index, other = false) {
        if (!option.hasOwnProperty('text'))
            return null;
        const placeholder = this.placeholder && `${this.placeholder} ${index + 1}`;
        return (index$1.h("div", { key: index, "data-option": true }, index$1.h("bce-input", { value: option.text, onInput: e => this.handleInput(e, index), onKeyDown: e => this.handleKeyDown(e, index), placeholder: placeholder }), this.renderMetadata(option), index$1.h("bce-menu", null, index$1.h("slot", { name: "option" }), this.allowColor && (index$1.h("bce-button", { icon: "fas:palette", onClick: () => this.handleColor(index) }, "Color")), this.allowImage && !other && (index$1.h("bce-button", { icon: "fas:image", onClick: () => this.handleImage(index) }, 'image' in option && option.image
            ? this.label.labelOCImageDelete
            : this.label.labelOCImageUpload)), this.value.length > 1 && (index$1.h("bce-button", { icon: "fas:trash", onClick: () => this.handleRemove(index) }, this.label.labelOCOptionRemove)))));
    }
    render() {
        const options = this.other ? this.value.slice(0, -1) : this.value;
        const other = this.other && this.value[this.value.length - 1];
        return [
            options.map((option, i) => this.renderOption(option, i)),
            other && this.renderOption(other, this.value.length - 1, true),
            index$1.h("slot", null),
            index$1.h("div", null, index$1.h("bce-button", { design: "text", icon: "fas:plus", onClick: () => this.addOption() }, this.label.labelOCOptionAdd), this.allowOther && (index$1.h("bce-button", { design: "text", icon: "fas:font", onClick: this.handleOther }, this.other
                ? this.label.labelOCOtherRemove
                : this.label.labelOCOtherAdd)), index$1.h("slot", { name: "action" }))
        ];
    }
    get el() { return index$1.getElement(this); }
    static get watchers() { return {
        "value": ["watchValue"]
    }; }
    static get style() { return ":host{position:relative;display:block;margin-bottom:40px}:host bce-icon,:host bce-input{--bce-input-height:40px;z-index:2}:host bce-button{text-transform:none}:host>:last-child{position:absolute;left:8px;bottom:-34px}:host [data-option]{position:relative}:host [data-option]>bce-input{margin:5px 0}:host [data-option]>bce-input input{padding:13px 38px}:host [data-option]>bce-icon{position:absolute;top:50%;left:10px;opacity:0.6;-webkit-transform:translateY(-50%);transform:translateY(-50%)}:host [data-option]>[data-meta]{position:absolute;right:30px;z-index:3;bottom:0;padding:4px}:host [data-option]>[data-meta] bce-icon{font-size:14px;opacity:0.5}:host [data-option]>bce-menu{position:absolute;right:0;top:0;z-index:3}\@media screen and (min-width: 1024px){:host [data-option]>bce-input:not([compact]) input{padding:6px 38px}}"; }
};
_server = new WeakMap();

exports.bce_option_creator = OptionCreator;
