import * as FAS from '@fortawesome/free-solid-svg-icons';
import { library } from '@fortawesome/fontawesome-svg-core';
import { h } from "@stencil/core";
import { Block } from '../../models/block';
import { ModuleFlow } from '../../models/module';
import { FlowTree } from '../../utils/flow-tree';
import { NativeEvent } from '../../utils/native-event';
import { getBlockCondition } from '../../utils/block-questions';
import { getTranslator } from '../../utils/translator';
library.add(FAS.faAngleRight, FAS.faPlus, FAS.faSearch, FAS.faTrash);
export class BceFlowEditor {
    constructor() {
        this.value = Object.assign(Object.assign({}, ModuleFlow.empty()), { start: { id: '<start>', version: 'v1' } });
        this.block = Block.empty();
        this.current = '';
        this.currentVersion = '';
        this.t = getTranslator();
        this.handleInput = (event) => {
            this.value = event.target.value;
            this.el.dispatchEvent(new NativeEvent('input'));
        };
        this.handleEndInput = async (event) => {
            event.cancelBubble = true;
            const editor = document.querySelector('bce-flow-graph');
            if (!editor)
                return;
            const end = event.target.value === 'true';
            if (!end) {
                const target = { id: this.current, version: this.currentVersion };
                return editor.addBlock(target);
            }
            const tasks = this.next.map(t => editor.unlink(this.current, t.id));
            await Promise.all(tasks);
            return;
        };
        this.handleConditionInput = (event, index) => {
            const target = event.target;
            if (!target)
                return;
            const current = this.next[index];
            const copy = [...this.next];
            copy.splice(index, 1, Object.assign(Object.assign({}, current), { condition: target.value }));
            this.value = Object.assign(Object.assign({}, this.value), { blocks: Object.assign(Object.assign({}, this.value.blocks), { [this.current]: copy }) });
            this.el.dispatchEvent(new NativeEvent('input'));
        };
        this.handleCompleteModule = () => {
            this.onComplete.emit();
        };
        this.handleShowBlock = () => {
            const { id, version } = this.next[0];
            this.onNode.emit({ id, version });
        };
        this.handleDeleteBlock = () => {
            const editor = document.querySelector('bce-flow-graph');
            if (!editor)
                return;
            const target = this.next[0];
            return editor.deleteBlock(target);
        };
        this.handleAddBlock = () => {
            const editor = document.querySelector('bce-flow-graph');
            if (!editor)
                return;
            const target = { id: this.current, version: this.currentVersion };
            return editor.addBlock(target);
        };
    }
    get conditionTemplate() {
        return [
            { name: 'date', label: 'Datum', input: 'date' },
            getBlockCondition(this.block)
        ];
    }
    get tree() {
        return new FlowTree(this.value);
    }
    get next() {
        return (this.value.blocks && this.value.blocks[this.current]) || [];
    }
    get end() {
        return !this.next.length || !this.next[0].id;
    }
    getLabel(ref) {
        return [
            this.t('me-flow-condition-screen'),
            this.tree.getLabel(ref.id, ref.version)
        ].join(' ');
    }
    renderEnd() {
        return (h("bce-button", { design: "text", onClick: this.handleCompleteModule },
            this.t('me-flow-action-end'),
            " ",
            h("bce-icon", { raw: "fas:angle-right" })));
    }
    renderSingleCtrl() {
        return [
            h("bce-button", { design: "text", icon: "fas:search", onClick: this.handleShowBlock }, this.t('me-flow-action-open')),
            h("bce-button", { design: "text", icon: "fas:trash", onClick: this.handleDeleteBlock }, this.t('me-flow-action-delete'))
        ];
    }
    renderConditionalCtrl() {
        return this.next.map((n, i) => (h("bce-input-container", { key: n.id, label: this.getLabel(n) }, this.next.length !== i + 1 ? (h("bce-condition", { template: this.conditionTemplate, value: n.condition, onInput: e => this.handleConditionInput(e, i) })) : (h("p", null, this.t('me-flow-condition-other'))))));
    }
    renderCtrl() {
        return [
            this.next.length > 1
                ? this.renderConditionalCtrl()
                : this.renderSingleCtrl(),
            h("bce-button", { design: "text", icon: "fas:plus", onClick: this.handleAddBlock }, this.t('me-flow-action-add'))
        ];
    }
    renderFooter() {
        return [
            h("bce-select", { type: "radio", key: '' + this.end, value: '' + this.end, onInput: this.handleEndInput },
                h("bce-option", { value: "true" }, this.t('me-flow-option-end')),
                h("bce-option", { value: "false" }, this.next.length > 1
                    ? this.t('me-flow-option-conditional')
                    : this.t('me-flow-option-next'))),
            this.end ? this.renderEnd() : this.renderCtrl()
        ];
    }
    render() {
        const title = this.t('me-flow-title');
        const subtitle = this.t('me-flow-subtitle');
        return [
            title && h("h5", null, title),
            subtitle && h("p", null, subtitle),
            h("bce-flow-graph", { value: this.value, current: this.current, existing: this.existing, editable: true, onInput: this.handleInput }),
            this.current && this.renderFooter()
        ];
    }
    static get is() { return "bce-flow-editor"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["bce-flow-editor.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["bce-flow-editor.css"]
    }; }
    static get properties() { return {
        "value": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "ModuleFlow",
                "resolved": "ModuleFlow",
                "references": {
                    "ModuleFlow": {
                        "location": "import",
                        "path": "../../models/module"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "defaultValue": "{\n    ...ModuleFlow.empty(),\n    start: { id: '<start>', version: 'v1' }\n  }"
        },
        "block": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "Block",
                "resolved": "Block",
                "references": {
                    "Block": {
                        "location": "import",
                        "path": "../../models/block"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "defaultValue": "Block.empty()"
        },
        "current": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "current",
            "reflect": false,
            "defaultValue": "''"
        },
        "currentVersion": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "current-version",
            "reflect": false,
            "defaultValue": "''"
        },
        "existing": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "string[]",
                "resolved": "string[] | undefined",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": ""
            }
        },
        "t": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "I18n.Translator",
                "resolved": "Translator<\"false\" | \"true\" | \"add-item\" | \"answer\" | \"category\" | \"column\" | \"delete-item\" | \"description\" | \"example\" | \"hide-item\" | \"icon\" | \"image\" | \"link\" | \"max\" | \"me-auto-play\" | \"me-block-subtitle\" | \"me-block-title\" | \"me-element-audio\" | \"me-element-checkbox-max\" | \"me-element-checkbox\" | \"me-element-download-placeholder\" | \"me-element-download\" | \"me-element-header-placeholder\" | \"me-element-header\" | \"me-element-icon\" | \"me-element-image\" | \"me-element-input-multiline\" | \"me-element-input\" | \"me-element-link\" | \"me-element-matrix\" | \"me-element-radio\" | \"me-element-slider\" | \"me-element-sort\" | \"me-element-table\" | \"me-element-text\" | \"me-element-video\" | \"me-flow-action-add\" | \"me-flow-action-delete\" | \"me-flow-action-end\" | \"me-flow-action-open\" | \"me-flow-condition-other\" | \"me-flow-condition-screen\" | \"me-flow-option-conditional\" | \"me-flow-option-end\" | \"me-flow-option-next\" | \"me-flow-subtitle\" | \"me-flow-title\" | \"me-module-advanced-options\" | \"me-module-graph-subtitle\" | \"me-module-graph-title\" | \"me-module-subtitle\" | \"me-module-title\" | \"me-option\" | \"me-orientation-h\" | \"me-orientation-v\" | \"me-orientation\" | \"me-other\" | \"me-question\" | \"me-required\" | \"min\" | \"name\" | \"row\" | \"show-item\" | \"step-size\" | \"text-left\" | \"text-right\" | \"text\" | \"upload-item\">",
                "references": {
                    "I18n": {
                        "location": "import",
                        "path": "@bce-technology/i18n"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "defaultValue": "getTranslator()"
        }
    }; }
    static get events() { return [{
            "method": "onNode",
            "name": "node",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "complexType": {
                "original": "Reference",
                "resolved": "{ id: string; version: string; }",
                "references": {
                    "Reference": {
                        "location": "import",
                        "path": "../../models/reference"
                    }
                }
            }
        }, {
            "method": "onComplete",
            "name": "complete-module",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            }
        }]; }
    static get elementRef() { return "el"; }
}
