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 { Directive } from "@angular/core";
import { AutoCompleteFieldEntry } from "./form/field/auto-complete/auto-complete-field-entry";
import { AutoCompleteField } from "./form/field/auto-complete/auto-complete-field.component";
import { CancelButton } from "./form/field/button/cancel-button";
import { FormDeleteButton } from "./form/field/button/form-delete-button";
import { OkButton } from "./form/field/button/ok-button";
import { PreviousButton } from "./form/field/button/previous-button";
import { CheckboxGroupField } from "./form/field/checkbox/checkbox-group.component";
import { DateField } from "./form/field/date/date-field.component";
import { FieldListField } from "./form/field/fieldList/field-list-field.component";
import { FileUploadField } from "./form/field/file-upload/file-upload.component";
import { SliderField } from "./form/field/slider/slider-field.component";
import { FormField } from "./form/field/form-field";
import { LabelField } from "./form/field/label/label-field.component";
import { NumberField } from "./form/field/number/number-field.component";
import { ProgressBarField } from "./form/field/progress-bar/progress-bar.component";
import { Radio } from "./form/field/radio/radio";
import { RadioGroupField } from "./form/field/radio/radio-group.component";
import { TextField } from "./form/field/text/text-field.component";
import { TranslationField } from "./form/field/translation/translation-field.component";
import { ValueField } from "./form/field/value-field";
import { FocusUtility } from "./form/focus-utility";
import { FormFunction } from "./form/form-function";
import { Form } from "./form/form.component";
import { ButtonGroup } from "./page/element/button-group/button-group.component";
import { BackButton } from "./page/element/button/back-button.component";
import { Button } from "./page/element/button/button.component";
import { LinkButton } from "./page/element/button/link-button.component";
import { PageDeleteButton } from "./page/element/button/page-delete-button.component";
import { ChartElement } from "./page/element/chart/chart.component";
import { CustomContainerPageElement } from "./page/element/custom/custom-container-page-element";
import { ElementList } from "./page/element/element-list/element-list.component";
import { InlineForm } from "./page/element/inline-form/inline-form";
import { PageLabel } from "./page/element/label/page-label.component";
import { List } from "./page/element/list/list.component";
import { Key, PageElement } from "./page/element/page-element";
import { Page } from "./page/page";
import { PathService } from "./service/path.service";
import { TranslationService } from "./service/translation.service";
import { KeyUtility } from "./utility/key-utility";
import { Breadcrumb } from "./page/element/breadcrumb/breadcrumb.component";
/* eslint-disable */
var PathAppComponent = /** @class */ (function () {
    function PathAppComponent(pathService, translationService) {
        var _this = this;
        this.pathService = pathService;
        this.translationService = translationService;
        /* eslint-enable */
        this._pageStack = [];
        this._formStack = [];
        this._texts = [];
        /* toggle navigation
        inspired by: https://angularfirebase.com/lessons/bootstrap-4-collapsable-navbar-work-with-angular */
        this.show = false;
        if (this.getBackendUrl() && this.getBackendUrl().length > 0) {
            this.pathService.serverGet(this.getBackendUrl(), "/ping", function (data) {
                var backendVersion = data["version"];
                if (backendVersion !== _this.getFrontendVersion()) {
                    backendVersion = "Version mismatch: Backend (" + backendVersion + "), Frontend (" + _this.getFrontendVersion() + "). " +
                        "Please clear cache or check server installation.";
                    window.alert(backendVersion);
                }
                _this._version = backendVersion;
                if (data["userId"] !== null && data["userId"] !== "") {
                    _this._userId = data["userId"];
                    _this.setCurrentPage(_this.getStartPage(), null);
                }
                if (data["languageCode"] !== null && data["languageCode"] !== "") {
                    sessionStorage.setItem("languageCode", data["languageCode"]);
                }
            }, function (err) {
                console.error(err);
            });
        }
        this.loadApplicationTexts();
    }
    Object.defineProperty(PathAppComponent.prototype, "version", {
        get: function () {
            return this._version;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PathAppComponent.prototype, "texts", {
        get: function () {
            return this._texts;
        },
        enumerable: false,
        configurable: true
    });
    PathAppComponent.prototype.getApplicationLogo = function () {
        return null;
    };
    PathAppComponent.prototype.isLoading = function () {
        return this.pathService.isLoading();
    };
    PathAppComponent.prototype.loadApplicationTexts = function () {
        this._texts["Logout"] = this.translationService.getText("Logout");
        this._texts["NotSignedIn"] = this.translationService.getText("NotSignedIn");
        this._texts["SignedInAs"] = this.translationService.getText("SignedInAs");
    };
    PathAppComponent.prototype.getUserId = function () {
        return this._userId;
    };
    PathAppComponent.prototype.login = function (event, userId, password) {
        var _this = this;
        var credentials = {};
        credentials["username"] = userId;
        credentials["password"] = password;
        this.pathService.serverPost(this.getBackendUrl(), "/login", credentials, function (data) {
            console.log("login ok, language code: " + data["languageCode"] + ", jwt:" + data["jwt"]);
            sessionStorage.setItem("languageCode", data["languageCode"]);
            _this._userId = userId;
            _this.loadApplicationTexts();
            _this.setCurrentPage(_this.getStartPage(), null); // set start page
        }, function (err) {
            _this.pathService.hideLoading();
            alert("Login failed.");
            console.error("failed login");
        });
    };
    PathAppComponent.prototype.logout = function () {
        sessionStorage.clear();
        console.log("logout user " + this._userId);
        this._userId = null;
        location.reload();
    };
    PathAppComponent.prototype.showUserForm = function () {
        this.setCurrentForm(this.getOwnUserForm(), new Key(0, "userId"), null, null); // TODO set correct key
    };
    PathAppComponent.prototype.closeCurrentForm = function () {
        this._formStack.pop();
    };
    PathAppComponent.prototype.refreshCurrentPage = function () {
        var pageStack = this._pageStack;
        var afterRefreshHandler = function () {
            // refresh all breadcrumb texts
            for (var k = 1; k < pageStack.length; k++) {
                var page = pageStack[k];
                // only if page name is derived from parent button
                if (page.parentPageElement && page.parentPageElement.getKey()) {
                    var parentPage = pageStack[k - 1]; // the parent page contains a button that defines the page name
                    for (var _i = 0, _a = parentPage.content; _i < _a.length; _i++) {
                        var element = _a[_i];
                        // search all lists of parent page
                        if (element instanceof List) {
                            var list = element;
                            // check if all buttons have unique keys
                            var keys = new Set();
                            var buttonCount = 0;
                            for (var _b = 0, _c = list.getContent(); _b < _c.length; _b++) {
                                var button = _c[_b];
                                buttonCount++;
                                keys.add(button.getKey().getName() + "-" + button.getKey().getKey());
                                if (keys.size !== buttonCount) {
                                    break;
                                }
                            }
                            // only update page name if list has unique keys
                            if (keys.size === buttonCount) {
                                for (var _d = 0, _e = list.getContent(); _d < _e.length; _d++) {
                                    var button = _e[_d];
                                    // compare key value and name and update page name
                                    if (page.parentPageElement.getKey().getKey() === button.getKey().getKey() &&
                                        page.parentPageElement.getKey().getName() === button.getKey().getName()) {
                                        page.name = PageElement.buildShortName(button.getName());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        };
        this.refreshPageStack(this._pageStack.length - 1, false, afterRefreshHandler);
    };
    PathAppComponent.prototype.refreshPageStack = function (index, clearSearch, afterRefreshHandler) {
        var refresh;
        if (this._pageStack[index].id === this.getStartPage() && clearSearch) {
            // refresh clean, without search text
            refresh = function (element) {
                var list = element;
                list.filterChanged(null);
                list.refresh(null, afterRefreshHandler);
            };
        }
        else {
            // refresh with search text
            refresh = function (element) {
                var list = element;
                list.refresh(list.searchText, afterRefreshHandler);
            };
        }
        var pageHasList = false;
        for (var _i = 0, _a = this._pageStack[index].content; _i < _a.length; _i++) {
            var element = _a[_i];
            if (element instanceof List) {
                refresh(element);
                pageHasList = true;
            }
        }
        if (!pageHasList && afterRefreshHandler) {
            afterRefreshHandler();
        }
        // breadcrumbs
        for (var k = index - 1; k > 0; k--) {
            var currentPage = this._pageStack[k];
            if (currentPage) {
                for (var _b = 0, _c = currentPage.content; _b < _c.length; _b++) {
                    var element = _c[_b];
                    if (element instanceof List) {
                        refresh(element);
                    }
                }
            }
        }
    };
    PathAppComponent.prototype.navigateBack = function (clearSearch) {
        var _this = this;
        if (clearSearch === void 0) { clearSearch = false; }
        var currentPageLength = this._pageStack.length;
        var afterRefreshHandler = function () {
            if (_this._pageStack.length === currentPageLength) {
                _this._pageStack.pop();
            }
        };
        this.refreshPageStack(this._pageStack.length - 2, clearSearch, afterRefreshHandler);
    };
    PathAppComponent.prototype.navigateToPage = function (pageNumber) {
        for (var k = this._pageStack.length - 1; k > pageNumber + 1; k--) {
            this._pageStack.pop();
        }
        this.navigateBack(true);
    };
    PathAppComponent.prototype.yesNo = function (text, yesHandler, noHandler) {
        var _this = this;
        var form = new Form(this.pathService, this);
        form.headerVisible = false;
        form.formFunction = new FormFunction();
        form.formFunction.save = function (data) {
            _this.closeCurrentForm();
            _this.refreshCurrentPage();
        };
        form.formFunction.cancel = function () {
            _this.closeCurrentForm();
        };
        var message = new TextField(form, this.translationService);
        message.type = "label";
        message.visible = true;
        message.labelVisible = false;
        message.setValue(text);
        message.width = 2;
        form.fields.push(message);
        var cancelButton = new CancelButton(form, this.translationService);
        cancelButton.type = "cancelButton";
        cancelButton.name = this.translationService.getText("Cancel");
        cancelButton.visible = true;
        form.fields.push(cancelButton);
        var okButton = new OkButton(form, this.translationService);
        okButton.type = "okButton";
        okButton.name = this.translationService.getText("Ok");
        okButton.visible = true;
        okButton.handler = {
            doClick: function (button) {
                yesHandler();
            }
        };
        form.fields.push(okButton);
        form.updateRows();
        this._formStack.push(form);
    };
    PathAppComponent.prototype.getCustomComponentClass = function (componentType) {
        console.log("Please define a type mapping for " + componentType + " in your App-Component.");
        return null;
    };
    PathAppComponent.prototype.setCurrentPage = function (pageId, parentPageElement) {
        var page = null;
        for (var _i = 0, _a = this.getGuiModel().application.pageList; _i < _a.length; _i++) {
            var modelPage = _a[_i];
            if (modelPage.id === pageId) {
                page = new Page(parentPageElement);
                page.id = pageId;
                page.name = this.translationService.getText(modelPage.name);
                if (parentPageElement != null) {
                    page.name = parentPageElement.name;
                }
                for (var _b = 0, _c = modelPage.elementList; _b < _c.length; _b++) {
                    var modelElement = _c[_b];
                    this.createPageElement(modelElement, parentPageElement, page);
                }
            }
        }
        if (page == null && pageId != null) {
            this.pathService.addAlert("Missing page", pageId);
        }
        else {
            this._pageStack.push(page);
        }
    };
    PathAppComponent.prototype.createPageElement = function (modelElement, parentPageElement, page) {
        var _a;
        var _this = this;
        var elements = [];
        switch (modelElement.type) {
            case "button":
            case "newButton":
                var button = new Button(this, this.pathService, this.translationService);
                button.parentPageElement = parentPageElement;
                button.fromJson(modelElement);
                if (modelElement["buttonhandler"] != null) {
                    button.handler = new (this.getHandlers()[modelElement["buttonhandler"]]);
                }
                elements.push(this.wrapSingleButton(button));
                break;
            case "deleteButton":
                var deleteButton = new PageDeleteButton(this, this.pathService, this.translationService);
                deleteButton.parentPageElement = parentPageElement;
                deleteButton.fromJson(modelElement);
                elements.push(this.wrapSingleButton(deleteButton));
                break;
            case "downloadButton": // deprecated
            case "linkButton":
                var linkButton = new LinkButton(this, this.pathService, this.translationService);
                linkButton.parentPageElement = parentPageElement;
                linkButton.fromJson(modelElement);
                elements.push(this.wrapSingleButton(linkButton));
                break;
            case "backbutton":
                var backButton = new BackButton(this, this.pathService, this.translationService);
                backButton.fromJson(modelElement);
                elements.push(this.wrapSingleButton(backButton));
                break;
            case "inlineForm":
                var inlineForm = new InlineForm(this, this.pathService, this.translationService);
                inlineForm.fromJson(modelElement);
                inlineForm.url = KeyUtility.translateUrl(modelElement["url"], inlineForm.getKey(), true, parentPageElement);
                inlineForm.loadNextForm(true);
                elements.push(inlineForm);
                break;
            case "list":
                var dynamicList = new List(this, this.pathService, this.translationService);
                dynamicList.parentPageElement = parentPageElement;
                dynamicList.fromJson(modelElement);
                // handler
                if (modelElement["handler"] != null) {
                    dynamicList.handler = new (this.getHandlers()[modelElement["handler"]]);
                }
                if (modelElement["buttonhandler"] != null) {
                    dynamicList.buttonHandler = new (this.getHandlers()[modelElement["buttonhandler"]]);
                }
                if (!dynamicList.searchRequired) {
                    dynamicList.refresh(null, null);
                }
                elements.push(dynamicList);
                break;
            case "ChartElement":
                var chart = new ChartElement(this, this.pathService, this.translationService);
                chart.fromJson(modelElement);
                chart.url = KeyUtility.translateUrl(modelElement["url"], null, false, parentPageElement);
                elements.push(chart);
                break;
            case "pageLabel":
                var pageLabel = new PageLabel(this, this.pathService, this.translationService);
                pageLabel.fromJson(modelElement);
                elements.push(pageLabel);
                break;
            case "elementList":
                var elementList = new ElementList(this, this.pathService, this.translationService);
                elementList.fromJson(modelElement);
                var elementListUrl = KeyUtility.translateUrl(modelElement["url"], null, false, parentPageElement);
                this.pathService.serverGet(this.getBackendUrl(), elementListUrl, function (data) {
                    for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
                        var dynamicElement = data_1[_i];
                        elements.push.apply(elements, _this.createPageElement(dynamicElement, parentPageElement, page));
                    }
                }, null);
                elements.push(elementList);
                break;
            case "buttonGroup":
                var buttonGroup = new ButtonGroup(this);
                buttonGroup.fromJson(modelElement);
                if (modelElement["buttons"]) {
                    for (var _i = 0, _b = modelElement["buttons"]; _i < _b.length; _i++) {
                        var buttonItem = _b[_i];
                        var buttonGroups = this.createPageElement(buttonItem, parentPageElement, null);
                        if (buttonGroups.length > 0) {
                            for (var _c = 0, _d = buttonGroups[0].buttons; _c < _d.length; _c++) {
                                var item = _d[_c];
                                buttonGroup.addButton(item);
                            }
                        }
                    }
                    buttonGroup.updateButtonBorders();
                }
                elements.push(buttonGroup);
                break;
            case "breadcrumb":
                var breadcrumb = new Breadcrumb(this);
                breadcrumb.fromJson(modelElement);
                elements.push(breadcrumb);
                break;
            default: {
                // call method to get custom component class
                var customContainerPageElement = new CustomContainerPageElement(this);
                customContainerPageElement.fromJson(modelElement);
                customContainerPageElement.typeClass = this.getCustomComponentClass(modelElement.type);
                elements.push(customContainerPageElement);
            }
        }
        for (var _e = 0, elements_1 = elements; _e < elements_1.length; _e++) {
            var element = elements_1[_e];
            if (modelElement["permissionUrl"] != null) {
                element.visible = false;
                var permissionUrl = KeyUtility.translateUrl(modelElement["permissionUrl"], null, false, parentPageElement);
                var permissionHandler = function (permissionElement) { return function (data) {
                    permissionElement.visible = data["permission"];
                }; };
                this.pathService.serverGet(this.getBackendUrl(), permissionUrl, permissionHandler(element), null);
            }
            if (!element.type) {
                element.type = modelElement.type;
            }
            element.parentPageElement = parentPageElement;
        }
        if (page && elements) {
            (_a = page.content).push.apply(_a, elements);
            page.updateRows();
        }
        return elements;
    };
    PathAppComponent.prototype.wrapSingleButton = function (button) {
        var buttonGroup = new ButtonGroup(this);
        buttonGroup.type = "buttonGroup";
        buttonGroup.addButton(button);
        buttonGroup.updateButtonBorders();
        buttonGroup.newRow = button.newRow;
        return buttonGroup;
    };
    PathAppComponent.prototype.setCurrentForm = function (formId, key, handler, parentPageElement) {
        var _this = this;
        var setCurrentForm = function () {
            // build form function
            var formFunction = new FormFunction();
            formFunction.save = function () {
                _this.closeCurrentForm();
                _this.refreshCurrentPage();
            };
            formFunction.cancel = function () {
                _this.closeCurrentForm();
            };
            formFunction.delete = function () {
                _this.closeCurrentForm();
                var parent = parentPageElement;
                if (parent != null && parent instanceof PageElement && parent.listElement) {
                    _this.refreshCurrentPage();
                }
                else {
                    _this.navigateBack();
                    _this.refreshCurrentPage();
                }
            };
            var form = _this.createForm(formId, key, handler, formFunction, parentPageElement);
            if (form != null) {
                _this._formStack.push(form);
            }
        };
        // check permission
        var modelForm = this.getModelForm(formId);
        if (modelForm != null && modelForm["permissionUrl"] != null) {
            var suffix = "/update";
            if (key == null) {
                suffix = "/create";
            }
            var permissionUrl = KeyUtility.translateUrl(modelForm["permissionUrl"] + suffix, key, false, parentPageElement);
            this.pathService.serverGet(this.getBackendUrl(), permissionUrl, function (data) {
                if (!data["permission"]) {
                    window.alert(_this.translationService.getText("NoPermissionError"));
                }
                else {
                    setCurrentForm();
                }
            }, null);
        }
        else {
            setCurrentForm();
        }
    };
    PathAppComponent.prototype.getModelForm = function (formId) {
        var result = null;
        for (var _i = 0, _a = this.getGuiModel().application.formList; _i < _a.length; _i++) {
            var modelForm = _a[_i];
            if (modelForm.id === formId) {
                result = modelForm;
            }
        }
        if (result == null && formId != null) {
            this.pathService.addAlert("Missing form", formId);
        }
        return result;
    };
    PathAppComponent.prototype.createForm = function (formId, key, handler, formFunction, parentPageElement) {
        var form = null;
        var modelForm = this.getModelForm(formId);
        if (modelForm != null) {
            // create form
            form = new Form(this.pathService, this);
            form.fromJson(modelForm);
            form.key = key;
            form.formFunction = formFunction;
            form.title = this.translationService.getText(modelForm.title);
            for (var _i = 0, _a = modelForm.formFieldList; _i < _a.length; _i++) {
                var modelFormField = _a[_i];
                // create form field
                var formField = this.createFormField(modelFormField, form, parentPageElement);
                form.fields.push(formField);
            }
            form.updateRows();
            // fetch data from backend
            if (form.url && form.key) {
                // button set a key on form, update mode, ignore urlDefaults
                this.populateForm(form, form.getKey(), parentPageElement);
            }
            else if (form.urlDefaults) {
                // no key, create mode
                var nullKey = new Key("null", "nullKey");
                this.populateForm(form, nullKey, parentPageElement);
            }
            if (form.url) {
                form.url = KeyUtility.translateUrl(form.url, key, true, parentPageElement);
            }
            // execute handler
            var handlerName = handler;
            if (handlerName == null) {
                handlerName = formId + "Handler";
            }
            if (this.getBeans()[formId] != null && this.getHandlers()[handlerName] != null) {
                var formBean = new (this.getBeans()[formId]);
                var formHandler = new (this.getHandlers()[handlerName]);
                for (var a = 0; a < form.fields.length; a++) {
                    if (form.fields[a].id != null) {
                        formBean[form.fields[a].id] = form.fields[a];
                    }
                }
                form.bean = formBean;
                formHandler.doLoad(form.bean);
                form.handler = formHandler;
            }
        }
        return form;
    };
    PathAppComponent.prototype.createDynamicForm = function () {
        return new Form(this.pathService, this);
    };
    PathAppComponent.prototype.populateForm = function (form, key, parentPageElement) {
        var url = KeyUtility.translateUrl(form.url, key, true, parentPageElement);
        this.pathService.serverGet(this.getBackendUrl(), url, function (data) {
            var _loop_1 = function (field) {
                if (data[field.id] != null && field instanceof ValueField) {
                    if (field instanceof RadioGroupField) {
                        // TODO general solution
                        var setValueOfRadioGroupFieldContextWrapper_1 = function () {
                            var f = field;
                            var v = data[field.id];
                            //noinspection TypeScriptUnresolvedFunction
                            setValueOfRadioGroupField_1(f, v);
                        };
                        var setValueOfRadioGroupField_1 = function (radioGroupField, value) {
                            if (!radioGroupField.created) {
                                console.log("Waiting for RadioGroupField " + radioGroupField.id);
                                console.log(radioGroupField.created);
                                window.setTimeout(setValueOfRadioGroupFieldContextWrapper_1, 50); // wait then try again
                                return;
                            }
                            console.log("setting radiogroupfield value");
                            if (value != null) {
                                value = value.toString(); // force radio key type string for angular2
                            }
                            radioGroupField.setValue(value);
                            radioGroupField.isInitialValueSet = true;
                        };
                        setValueOfRadioGroupFieldContextWrapper_1();
                    }
                    else {
                        field.setValue(data[field.id]);
                        field.isInitialValueSet = true;
                    }
                }
                if (field instanceof FieldListField) {
                    var setValueOfFieldListFieldContextWrapper_1 = function () {
                        var f = field;
                        var d = data;
                        //noinspection TypeScriptUnresolvedFunction
                        setValueOfFieldListField_1(f, d);
                    };
                    var setValueOfFieldListField_1 = function (fieldListField, value) {
                        if (!field.created) {
                            console.log("Waiting for FieldListField... ");
                            setTimeout(setValueOfFieldListFieldContextWrapper_1, 50); // wait then try again
                            return;
                        }
                        // update fields
                        for (var _i = 0, _a = field.subfields; _i < _a.length; _i++) {
                            var subfield = _a[_i];
                            if (data[subfield.id] != null) {
                                subfield.setValue(data[subfield.id]);
                                subfield.isInitialValueSet = true;
                            }
                        }
                        setTimeout(function () { FocusUtility.focusFirstField(field.getForm()); });
                    };
                    setValueOfFieldListFieldContextWrapper_1();
                }
            };
            for (var _i = 0, _a = form.fields; _i < _a.length; _i++) {
                var field = _a[_i];
                _loop_1(field);
            }
        }, null);
    };
    PathAppComponent.prototype.createFormField = function (modelFormField, form, parentPageElement) {
        var _this = this;
        var formField = null;
        switch (modelFormField.type) {
            case "text": {
                formField = new TextField(form, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "translation": {
                formField = new TranslationField(form, this.pathService, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "number": {
                formField = new NumberField(form, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "label": {
                formField = new LabelField(form, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "fieldList": {
                formField = new FieldListField(form, this.translationService);
                formField.name = "list";
                formField.fromJson(modelFormField);
                if (modelFormField["url"] != null) {
                    var fieldListUrl = KeyUtility.translateUrl(modelFormField["url"], form.getKey(), false, parentPageElement);
                    var modelId_1 = modelFormField["id"];
                    this.pathService.serverGet(this.getBackendUrl(), fieldListUrl, function (data) {
                        var counter = 1;
                        for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
                            var item = data_2[_i];
                            var dynamicField = _this.createFormField(item, form, parentPageElement);
                            dynamicField.name = item["name"]; // do not use translation service
                            dynamicField.id = modelId_1 + counter;
                            formField.subfields.push(dynamicField);
                            counter++;
                        }
                        form.updateRows();
                        formField.created = true;
                    }, null);
                }
                break;
            }
            case "date": {
                formField = new DateField(form, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "autocomplete": {
                var autoCompleteFormField = new AutoCompleteField(form, this.translationService, this.pathService);
                autoCompleteFormField.detailForm = modelFormField["form"];
                autoCompleteFormField.wordSearchEnabled = modelFormField["wordSearchEnabled"];
                if (modelFormField["data"] != null) {
                    var data = [];
                    var k = 0;
                    for (var _i = 0, _a = modelFormField["data"]; _i < _a.length; _i++) {
                        var item = _a[_i];
                        var entry = new AutoCompleteFieldEntry();
                        entry.text = item;
                        entry.key = k;
                        data.push(entry);
                        k++;
                    }
                    autoCompleteFormField.data = data;
                    autoCompleteFormField.dataLoaded = true;
                }
                else if (modelFormField["url"] != null) {
                    var autoCompleteFormFieldUrl = KeyUtility.translateUrl(modelFormField["url"], form.key, false, parentPageElement);
                    autoCompleteFormField.url = autoCompleteFormFieldUrl;
                    autoCompleteFormField.load();
                }
                else {
                    autoCompleteFormField.dataLoaded = true;
                }
                formField = autoCompleteFormField;
                formField.fromJson(modelFormField);
                break;
            }
            case "RadioGroupField": {
                var radioGroupFormField = new RadioGroupField(form, this.translationService);
                if (modelFormField["url"] != null) {
                    var radiosUrl = KeyUtility.translateUrl(modelFormField["url"], form.getKey(), false, parentPageElement);
                    var radioLoader = function (rgField) { return function (data) {
                        for (var _i = 0, data_3 = data; _i < data_3.length; _i++) {
                            var item = data_3[_i];
                            var radio = new Radio(form, _this.translationService);
                            radio.name = item["name"];
                            radio.key = item["key"]["key"].toString(); // force radio key type string for angular2
                            if (radio.key === item["defaultKey"]) {
                                rgField.setValue(radio.key);
                            }
                            rgField.radios.push(radio);
                        }
                        rgField.created = true;
                        console.log("radio group field created: " + rgField.id);
                    }; };
                    var radioLoaderForField = radioLoader(radioGroupFormField);
                    this.pathService.serverGet(this.getBackendUrl(), radiosUrl, radioLoaderForField, null);
                }
                else {
                    radioGroupFormField.created = true;
                }
                radioGroupFormField.fromJson(modelFormField);
                formField = radioGroupFormField;
                break;
            }
            case "CheckboxGroupField": {
                var checkboxGroupField = new CheckboxGroupField(form, this.translationService);
                checkboxGroupField.fromJson(modelFormField);
                formField = checkboxGroupField;
                break;
            }
            case "ProgressBarField": {
                var progressBarField = new ProgressBarField(form, this.translationService);
                progressBarField.fromJson(modelFormField);
                formField = progressBarField;
                break;
            }
            case "okButton": {
                formField = new OkButton(form, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "cancelButton": {
                formField = new CancelButton(form, this.translationService);
                formField.fromJson(modelFormField);
                break;
            }
            case "deleteButton": {
                formField = new FormDeleteButton(form, this.translationService);
                formField.fromJson(modelFormField);
                if (form.key == null) {
                    formField.visible = false;
                }
                break;
            }
            case "previousButton": {
                formField = new PreviousButton(form, this.translationService);
                formField.fromJson(modelFormField);
                if (form.key == null) {
                    formField.visible = false;
                }
                break;
            }
            case "fileUpload": {
                formField = new FileUploadField(form, this.translationService);
                modelFormField["url"] = KeyUtility.translateUrl(modelFormField["url"], form.getKey(), false, parentPageElement);
                formField.fromJson(modelFormField);
                break;
            }
            case "SliderField": {
                var sliderField = new SliderField(form, this.translationService);
                sliderField.fromJson(modelFormField);
                formField = sliderField;
                break;
            }
            default: {
                formField = new FormField(form, this.translationService);
                formField.fromJson(modelFormField);
            }
        }
        // Field permission (move code to FormField)
        if (modelFormField["permissionUrl"] != null) {
            formField.readonly = false;
            var permissionUrl = KeyUtility.translateUrl(modelFormField["permissionUrl"], formField.getForm().getKey(), false, parentPageElement);
            var permissionHandler = function (permissionElement) { return function (data) {
                permissionElement.readonly = !data["permission"];
            }; };
            this.pathService.serverGet(formField.getForm().getApp().getBackendUrl(), permissionUrl, permissionHandler(formField), null);
        }
        // search parents for defaultKey
        if (formField instanceof ValueField && modelFormField["defaultKey"] != null) {
            var pageElement = parentPageElement;
            while (pageElement != null) {
                if (pageElement.getKey() != null && pageElement.getKey().getName() === modelFormField["defaultKey"]) {
                    formField.setValue(pageElement.getKey().getKey());
                    formField.isInitialValueSet = true;
                    pageElement = null;
                }
                else {
                    pageElement = pageElement.getParent();
                }
            }
        }
        return formField;
    };
    PathAppComponent.prototype.toggleCollapse = function () {
        this.show = !this.show;
    };
    PathAppComponent = __decorate([
        Directive({
            selector: "path-application-2",
            providers: [PathService, TranslationService]
        }),
        __metadata("design:paramtypes", [PathService, TranslationService])
    ], PathAppComponent);
    return PathAppComponent;
}());
export { PathAppComponent };
//# sourceMappingURL=path-app.component.js.map