var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
import { r as registerInstance, d as createEvent, h, g as getElement } from './index-b13326fc.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;
var OptionCreator = /** @class */ (function () {
    function class_1(hostRef) {
        var _this = this;
        registerInstance(this, hostRef);
        this.value = [];
        _server.set(this, window.BCE.file);
        this.handleInput = function (event, index) {
            var input = event.target;
            if (!input)
                return;
            // Update value
            var copy = __spreadArrays(_this.value);
            var update = Object.assign(Object.assign({}, _this.value[index]), { text: input.value });
            copy.splice(index, 1, update);
            _this.updateValue(copy);
            event.stopPropagation();
        };
        this.handleKeyDown = function (event, index) { return __awaiter(_this, void 0, void 0, function () {
            var target;
            return __generator(this, function (_a) {
                switch (event.keyCode) {
                    case 8: // Backspace
                        target = event.target;
                        if (!target.value && index != 0) {
                            this.focusOption(index - 1);
                            this.handleRemove(index);
                        }
                        return [2 /*return*/];
                    case 13: //Enter
                        return [2 /*return*/, this.addOption()];
                }
                return [2 /*return*/];
            });
        }); };
        this.handleOther = function () {
            _this.other = !_this.other;
            _this.value = _this.other
                ? __spreadArrays(_this.value, [{ text: _this.t('me-other') || '' }]) : _this.value.slice(0, -1);
            _this.onOther.emit(_this.other);
        };
        this.handleRemove = function (index) {
            var copy = __spreadArrays(_this.value);
            copy.splice(index, 1);
            _this.updateValue(copy);
        };
        this.handleColor = function (index) { };
        this.handleImage = function (index) {
            var current = _this.value[index];
            if ('image' in current && current.image)
                _this.deleteImage(current, index);
            else
                _this.uploadImage(index);
        };
        this.onOther = createEvent(this, "other", 7);
    }
    class_1.prototype.watchValue = function (value) {
        if (!value.length)
            this.addOption(false);
    };
    class_1.prototype.addOption = function (focus) {
        if (focus === void 0) { focus = true; }
        return __awaiter(this, void 0, void 0, function () {
            var insert, value;
            return __generator(this, function (_a) {
                insert = { text: '' };
                value = this.other
                    ? __spreadArrays(this.value.slice(0, -1), [insert], this.value.slice(-1)) : __spreadArrays(this.value, [insert]);
                this.updateValue(value);
                if (focus)
                    this.focusLast(true);
                return [2 /*return*/];
            });
        });
    };
    class_1.prototype.focusLast = function (nextTick) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.focusOption(-(this.other ? 2 : 1), nextTick)];
            });
        });
    };
    class_1.prototype.focusOption = function (index, nextTick) {
        if (nextTick === void 0) { nextTick = false; }
        return __awaiter(this, void 0, void 0, function () {
            var query, options, option, input;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!nextTick) return [3 /*break*/, 2];
                        return [4 /*yield*/, new Promise(function (res) { return setTimeout(res, 100); })];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        query = '[data-option] bce-input';
                        options = this.el.shadowRoot.querySelectorAll(query);
                        option = options[index < 0 ? options.length + index : index];
                        input = option && option.shadowRoot.querySelector('input');
                        // Set focus to new element
                        if (input)
                            input.focus();
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.uploadImage = function (index) {
        return __awaiter(this, void 0, void 0, function () {
            var root, upload, file, copy;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        root = document.querySelector('bce-root');
                        upload = document.createElement('bce-upload');
                        upload.accept = 'image/*';
                        upload.active = true;
                        upload.dialog = true;
                        return [4 /*yield*/, root.execute(upload, function (res) {
                                upload.addEventListener('input', function (event) {
                                    var target = event.target;
                                    res(target.value[0]);
                                });
                            }, { display: true })];
                    case 1:
                        file = _a.sent();
                        copy = __spreadArrays(this.value);
                        copy.splice(index, 1, Object.assign(Object.assign({}, this.value[index]), { image: file }));
                        // Emit value
                        console.log(copy);
                        return [2 /*return*/];
                }
            });
        });
    };
    class_1.prototype.deleteImage = function (option, index) {
        if (!('image' in option) || !option.image)
            return;
        __classPrivateFieldGet(this, _server).delete(option.image, {});
        // Update value
        var copy = __spreadArrays(this.value);
        var value = Object.assign({}, this.value[index]);
        if ('image' in value)
            delete value.image;
        copy.splice(index, 1, value);
        this.updateValue(copy);
    };
    class_1.prototype.updateValue = function (value) {
        this.value = value;
        var e = new globalThis.Event('input', { bubbles: true, composed: true });
        this.el.dispatchEvent(e);
    };
    class_1.prototype.componentWillLoad = function () {
        this.watchValue(this.value);
    };
    class_1.prototype.renderTooltip = function (icon, content) {
        if (!content)
            return null;
        return (h("bce-tooltip", { placement: "left", icon: icon }, content));
    };
    class_1.prototype.renderMetadata = function (option) {
        if (!('image' in option))
            return;
        return h("div", { "data-meta": true }, this.renderTooltip('fas:image', option.image));
    };
    class_1.prototype.renderOption = function (option, index, other) {
        var _this = this;
        if (other === void 0) { other = false; }
        if (!option.hasOwnProperty('text'))
            return null;
        var placeholder = this.placeholder && this.placeholder + " " + (index + 1);
        return (h("div", { key: index, "data-option": true }, h("bce-input", { value: option.text, onInput: function (e) { return _this.handleInput(e, index); }, onKeyDown: function (e) { return _this.handleKeyDown(e, index); }, placeholder: placeholder }), this.renderMetadata(option), h("bce-menu", null, h("slot", { name: "option" }), this.allowColor && (h("bce-button", { icon: "fas:palette", onClick: function () { return _this.handleColor(index); } }, "Color")), this.allowImage && !other && (h("bce-button", { icon: "fas:image", onClick: function () { return _this.handleImage(index); } }, 'image' in option && option.image
            ? this.t('delete-item', { item: this.t('image') })
            : this.t('upload-item', { item: this.t('image') }))), this.value.length > 1 && (h("bce-button", { icon: "fas:trash", onClick: function () { return _this.handleRemove(index); } }, this.t('delete-item', { item: this.label }))))));
    };
    class_1.prototype.render = function () {
        var _this = this;
        var options = this.other ? this.value.slice(0, -1) : this.value;
        var other = this.other && this.value[this.value.length - 1];
        return [
            options.map(function (option, i) { return _this.renderOption(option, i); }),
            other && this.renderOption(other, this.value.length - 1, true),
            h("slot", null),
            h("div", null, h("bce-button", { design: "text", icon: "fas:plus", onClick: function () { return _this.addOption(); } }, this.t('add-item', { item: this.label })), this.allowOther && (h("bce-button", { design: "text", icon: "fas:font", onClick: this.handleOther }, this.other
                ? this.t('delete-item', { item: "\"" + this.t('me-other') + "\"" })
                : this.t('add-item', { item: "\"" + this.t('me-other') + "\"" }))), h("slot", { name: "action" }))
        ];
    };
    Object.defineProperty(class_1.prototype, "el", {
        get: function () { return getElement(this); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(class_1, "watchers", {
        get: function () {
            return {
                "value": ["watchValue"]
            };
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(class_1, "style", {
        get: function () { 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}}"; },
        enumerable: true,
        configurable: true
    });
    return class_1;
}());
_server = new WeakMap();
export { OptionCreator as bce_option_creator };
