var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, EventEmitter, forwardRef, Inject, Optional, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material';
import { InputConverter, OFormComponent, OFormValue, SQLTypes } from 'ontimize-web-ngx';
import { ODynamicFormComponent } from 'ontimize-web-ngx-dynamicform';
import { BehaviorSubject } from 'rxjs';
import { ComponentSettingsDialogComponent } from './component-settings-dialog.component';
import { OComponentData } from './ontimize-components-data';
import { ComponentsDataService } from './services';
import { ArrayList } from './utils';
var ODynamicFormBuilderComponent = (function () {
    function ODynamicFormBuilderComponent(dialog, componentsDataService, parentForm) {
        this.dialog = dialog;
        this.componentsDataService = componentsDataService;
        this.parentForm = parentForm;
        this.autoBinding = true;
        this.autoRegistering = true;
        this.formDefinition$ = new BehaviorSubject(null);
        this.componentsArray = new ArrayList();
        this.render = new EventEmitter();
        this.onFormDefinitionUpdate = new EventEmitter();
        this.innerFormDefinition = null;
    }
    ODynamicFormBuilderComponent.prototype.ngOnInit = function () {
        this.getControl();
        var setDefaultDef = !this.formDefinition;
        if (setDefaultDef) {
            this.innerFormDefinition = {
                components: []
            };
        }
        if (this.parentForm) {
            this.registerFormListeners();
            this._isReadOnly = this.parentForm.isInInitialMode();
        }
        else {
            this._isReadOnly = false;
        }
    };
    ODynamicFormBuilderComponent.prototype.registerFormListeners = function () {
        if (this.parentForm) {
            this.parentForm.registerFormComponent(this);
            this.parentForm.registerSQLTypeFormComponent(this);
        }
    };
    ODynamicFormBuilderComponent.prototype.ngOnDestroy = function () {
        this.unregisterFormListeners();
    };
    ODynamicFormBuilderComponent.prototype.unregisterFormListeners = function () {
        if (this.parentForm) {
            this.parentForm.unregisterFormComponent(this);
            this.parentForm.unregisterSQLTypeFormComponent(this);
        }
    };
    ODynamicFormBuilderComponent.prototype.getValue = function () {
    };
    ODynamicFormBuilderComponent.prototype.clearValue = function () {
    };
    ODynamicFormBuilderComponent.prototype.setValue = function (val) {
        this.formDefinition = val;
    };
    ODynamicFormBuilderComponent.prototype.getAttribute = function () {
        if (this.oattr) {
            return this.oattr;
        }
        return undefined;
    };
    ODynamicFormBuilderComponent.prototype.getSQLType = function () {
        return SQLTypes.OTHER;
    };
    ODynamicFormBuilderComponent.prototype.reloadInnerFormMode = function () {
        this.innerForm.setFormMode(this.innerForm.mode);
    };
    ODynamicFormBuilderComponent.prototype.onDynamicFormRendered = function () {
        this.reloadInnerFormMode();
        if (this.render) {
            this.render.emit(true);
        }
    };
    Object.defineProperty(ODynamicFormBuilderComponent.prototype, "data", {
        set: function (value) {
            var formDef;
            if (value instanceof OFormValue) {
                formDef = value.value;
            }
            if (!formDef) {
                formDef = {
                    components: []
                };
            }
            this.formDefinition = formDef;
        },
        enumerable: true,
        configurable: true
    });
    ODynamicFormBuilderComponent.prototype.isAutomaticBinding = function () {
        return this.autoBinding;
    };
    ODynamicFormBuilderComponent.prototype.isAutomaticRegistering = function () {
        return this.autoRegistering;
    };
    ODynamicFormBuilderComponent.prototype.getComponentsFromJSON = function (componentsJSON, parent) {
        for (var i = 0; i < componentsJSON.length; i++) {
            var comp = Object.assign({}, componentsJSON[i]);
            if (comp.hasOwnProperty('ontimize-directive')) {
                var compData = this.componentsDataService.getOntimizeComponentData(comp['ontimize-directive']);
                delete comp['ontimize-directive'];
                compData.setConfiguredInputs(comp);
                if (compData.isContainer() && comp.hasOwnProperty('children') && comp.children.length) {
                    this.getComponentsFromJSON(comp.children, compData.children);
                }
                parent.push(compData);
            }
        }
    };
    Object.defineProperty(ODynamicFormBuilderComponent.prototype, "formDefinition", {
        get: function () {
            return this.innerFormDefinition;
        },
        set: function (definition) {
            var definitionJSON = definition;
            if (typeof definition === 'string') {
                try {
                    definitionJSON = JSON.parse(definition);
                }
                catch (e) {
                    console.error('set formDefinition error');
                }
            }
            this.componentsArray = new ArrayList();
            if (definitionJSON && definitionJSON.hasOwnProperty('components') && definitionJSON.components.length) {
                this.getComponentsFromJSON(definitionJSON.components, this.componentsArray);
            }
            this.innerFormDefinition = definitionJSON;
            this.formDefinition$.next(this.innerFormDefinition);
        },
        enumerable: true,
        configurable: true
    });
    ODynamicFormBuilderComponent.prototype.definitionToString = function () {
        return JSON.stringify(this.formDefinition);
    };
    ODynamicFormBuilderComponent.prototype.onUpdateComponents = function () {
        var componentsParsedArray = [];
        this.getComponentsJson(this.componentsArray, componentsParsedArray);
        this.formDefinition = { components: componentsParsedArray };
        this.onFormDefinitionUpdate.emit(this.innerFormDefinition);
    };
    ODynamicFormBuilderComponent.prototype.getComponentsJson = function (components, parent) {
        for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
            var comp = components_1[_i];
            var compInputs = comp.getConfiguredInputs();
            var compObj = Object.assign({}, compInputs);
            compObj['ontimize-directive'] = comp.getDirective();
            if (comp.isContainer()) {
                compObj['children'] = [];
                this.getComponentsJson(comp.getChildren(), compObj['children']);
            }
            parent.push(compObj);
        }
    };
    ODynamicFormBuilderComponent.prototype.openSettingsDialog = function (component, args) {
        var self = this;
        var dialogRef = this.dialog.open(ComponentSettingsDialogComponent, {
            width: '60%',
            disableClose: true,
            panelClass: ['o-dialog-class', 'o-dynamic-form-builder-dialog']
        });
        dialogRef.componentInstance.setTemplateInputsData(component.getTemplateInputsData());
        dialogRef.componentInstance.setComponent(component);
        dialogRef.afterClosed().subscribe(function (newComponent) {
            if (newComponent !== false && newComponent instanceof OComponentData) {
                var emptyArgs = !Object.keys(args || {}).length;
                if (emptyArgs) {
                    self.componentsArray.unshift(newComponent);
                }
                else if (args.hasOwnProperty('previousSibling')) {
                    self._insertElement(args.previousSibling.getComponentAttr(), self.componentsArray, newComponent);
                }
                else if (args.hasOwnProperty('parent')) {
                    args.parent.addChild(newComponent);
                }
                self.onUpdateComponents();
            }
        });
    };
    ODynamicFormBuilderComponent.prototype.getComponentsArray = function () {
        return this.componentsArray.toArray();
    };
    ODynamicFormBuilderComponent.prototype.onAddComponent = function (args) {
        var component = args.component;
        var previousSibling = this.getOComponentData(args.previousSibling);
        var parent = this.getOComponentData(args.parent);
        var dialogArgs = {};
        if (previousSibling) {
            dialogArgs['previousSibling'] = previousSibling;
        }
        if (parent) {
            dialogArgs['parent'] = parent;
        }
        this.openSettingsDialog(component, dialogArgs);
    };
    ODynamicFormBuilderComponent.prototype.onMoveComponent = function (args) {
        var component = args.component;
        this.onDeleteComponent(args);
        var newComponent = this.cloneComponent(component);
        if (args.hasOwnProperty('previousSibling')) {
            this._insertElement(args.previousSibling.getComponentAttr(), this.componentsArray, newComponent);
        }
        else if (args.hasOwnProperty('parent')) {
            var parent_1 = this._searchElement(args.parent.getComponentAttr(), this.componentsArray);
            if (parent_1) {
                parent_1.addChild(newComponent);
            }
        }
        else {
            this.componentsArray.unshift(newComponent);
        }
        this.onUpdateComponents();
    };
    ODynamicFormBuilderComponent.prototype.onEditComponentSettings = function (args) {
        var component = this.getOComponentData(args.component);
        if (!component) {
            return;
        }
        this.openSettingsDialog(component, { edit: true });
    };
    ODynamicFormBuilderComponent.prototype.onDeleteComponent = function (args) {
        var component = this.getOComponentData(args.component);
        if (!component) {
            return;
        }
        this._removeElement(component.getComponentAttr(), this.componentsArray);
        this.onUpdateComponents();
    };
    ODynamicFormBuilderComponent.prototype.getOComponentData = function (fieldComponent) {
        if (!fieldComponent) {
            return undefined;
        }
        var component = this._searchElement(fieldComponent.getComponentAttr(), this.componentsArray);
        return component;
    };
    ODynamicFormBuilderComponent.prototype.cloneComponent = function (component) {
        return this._cloneComponentData(component.settings);
    };
    Object.defineProperty(ODynamicFormBuilderComponent.prototype, "isReadOnly", {
        get: function () {
            return this._isReadOnly;
        },
        set: function (value) {
            this._isReadOnly = value;
        },
        enumerable: true,
        configurable: true
    });
    ODynamicFormBuilderComponent.prototype.getControl = function () {
        if (!this._fControl) {
            this._fControl = new FormControl();
        }
        return this._fControl;
    };
    ODynamicFormBuilderComponent.prototype.getFormControl = function () {
        return this._fControl;
    };
    ODynamicFormBuilderComponent.prototype.hasError = function (error) {
        return this._fControl && this._fControl.hasError(error);
    };
    ODynamicFormBuilderComponent.prototype._searchElement = function (id, array) {
        var r;
        for (var i = 0; i < array.length; i++) {
            if (id === array[i].getComponentAttr()) {
                return array[i];
            }
            if (array[i].children && array[i].children.length > 0) {
                if ((r = this._searchElement(id, array[i].children)) !== null) {
                    return r;
                }
            }
        }
        return null;
    };
    ODynamicFormBuilderComponent.prototype._insertElement = function (id, array, newComponent) {
        for (var i = 0; i < array.length; i++) {
            if (id === array[i].getComponentAttr()) {
                array.splice(i + 1, 0, newComponent);
            }
            if (array[i].children) {
                this._insertElement(id, array[i].children, newComponent);
            }
        }
    };
    ODynamicFormBuilderComponent.prototype._removeElement = function (id, array) {
        for (var i = 0; i < array.length; i++) {
            if (id === array[i].getComponentAttr()) {
                array.splice(i, 1);
            }
            if (array[i] && array[i].children) {
                this._removeElement(id, array[i].children);
            }
        }
    };
    ODynamicFormBuilderComponent.prototype._cloneComponentData = function (settings) {
        var _this = this;
        var newComponent = this.componentsDataService.getOntimizeComponentData(settings['ontimize-directive']);
        delete settings['ontimize-directive'];
        newComponent.setConfiguredInputs(settings);
        if (settings.children) {
            settings.children.forEach(function (child) {
                newComponent.addChild(_this._cloneComponentData(child));
            });
        }
        return newComponent;
    };
    ODynamicFormBuilderComponent.decorators = [
        { type: Component, args: [{
                    selector: 'o-dynamic-form-builder',
                    template: "\n    <app-menu id=\"FORM_BUILDER_MANAGER\" class=\"framed\" ui-element=\"sidebar\" [drag-enabled]=\"!isReadOnly\" fxFlex>\n      <div fxLayout=\"row\" fxLayoutAlign=\"center center\" class=\"dynamicform-container\" fxFill>\n        <div fxLayout=\"row\" fxLayoutAlign=\"center\" class=\"mat-elevation-z1 dropzone-container\" fxFlex=\"90\">\n          <extended-form #innerForm show-header=\"false\" query-on-init=\"false\" fxFlex>\n            <o-dynamic-form #dynamicForm query-on-init=\"false\" register-in-parent-form=\"false\" [form-definition]=\"formDefinition$ | async\"\n              [edit-mode]=\"!isReadOnly\" (onAddComponent)=\"onAddComponent($event)\" (onMoveComponent)=\"onMoveComponent($event)\"\n              (onEditComponentSettings)=\"onEditComponentSettings($event)\" (onDeleteComponent)=\"onDeleteComponent($event)\"\n              (render)=\"onDynamicFormRendered()\">\n            </o-dynamic-form>\n          </extended-form>\n        </div>\n      </div>\n    </app-menu>\n  ",
                    styles: ["\n    ::-webkit-scrollbar{width:5px;height:4px}::-webkit-scrollbar-button{width:0px;height:0px}::-webkit-scrollbar-thumb{background:rgba(255,223,119,0.2)}::-webkit-scrollbar-track{background:rgba(17,17,17,0.3)}::-webkit-scrollbar-thumb:active{background:rgba(17,17,17,0.3)}::-webkit-scrollbar-thumb,::-webkit-scrollbar-track{border:none}::-webkit-scrollbar-track:hover,::-webkit-scrollbar-track:active,::-webkit-scrollbar-corner{background:transparent}o-dynamic-form-builder .dynamicform-container{height:100%}o-dynamic-form-builder .dynamicform-container .dropzone-container{height:95%;overflow:auto}\n  "],
                    inputs: [
                        'oattr :attr',
                        'autoBinding: automatic-binding',
                        'autoRegistering: automatic-registering',
                        'formDefinition: form-definition'
                    ],
                    outputs: [
                        'render',
                        'onFormDefinitionUpdate'
                    ],
                    encapsulation: ViewEncapsulation.None
                },] },
    ];
    ODynamicFormBuilderComponent.ctorParameters = function () { return [
        { type: MatDialog },
        { type: ComponentsDataService },
        { type: OFormComponent, decorators: [{ type: Optional }, { type: Inject, args: [forwardRef(function () { return OFormComponent; }),] }] }
    ]; };
    ODynamicFormBuilderComponent.propDecorators = {
        innerForm: [{ type: ViewChild, args: ['innerForm',] }],
        dynamicForm: [{ type: ViewChild, args: ['dynamicForm',] }]
    };
    __decorate([
        InputConverter(),
        __metadata("design:type", Boolean)
    ], ODynamicFormBuilderComponent.prototype, "autoBinding", void 0);
    __decorate([
        InputConverter(),
        __metadata("design:type", Boolean)
    ], ODynamicFormBuilderComponent.prototype, "autoRegistering", void 0);
    return ODynamicFormBuilderComponent;
}());
export { ODynamicFormBuilderComponent };
//# sourceMappingURL=o-dynamic-form-builder.component.js.map