var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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, Input, QueryList, ViewChildren } from '@angular/core';
import { AbstractFieldWriteComponent } from '../base-field/abstract-field-write.component';
import { CaseField } from '../../../domain/definition/case-field.model';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { FormValidatorsService } from '../../../services/form/form-validators.service';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { RemoveDialogComponent } from '../../dialogs/remove-dialog/remove-dialog.component';
import { ScrollToService } from '@nicky-lenaers/ngx-scroll-to';
import { finalize } from 'rxjs/operators';
import { ProfileNotifier } from '../../../services';
var WriteCollectionFieldComponent = /** @class */ (function (_super) {
    __extends(WriteCollectionFieldComponent, _super);
    function WriteCollectionFieldComponent(formValidatorsService, dialog, scrollToService, profileNotifier) {
        var _this = _super.call(this) || this;
        _this.formValidatorsService = formValidatorsService;
        _this.dialog = dialog;
        _this.scrollToService = scrollToService;
        _this.profileNotifier = profileNotifier;
        _this.caseFields = [];
        return _this;
    }
    WriteCollectionFieldComponent.prototype.ngOnInit = function () {
        var _this = this;
        if (!this.isExpanded) { // meaning I am not rendered on the search/workbasket input filter
            this.profileNotifier.profile.subscribe(function (_) { return _this.profile = _; });
        }
        this.caseField.value = this.caseField.value || [];
        this.formArray = this.registerControl(new FormArray([]));
    };
    WriteCollectionFieldComponent.prototype.buildCaseField = function (item, index) {
        return this.newCaseField(index, item);
    };
    WriteCollectionFieldComponent.prototype.newCaseField = function (index, item) {
        return Object.assign(new CaseField(), {
            id: index.toString(),
            field_type: this.caseField.field_type.collection_field_type,
            display_context: this.caseField.display_context,
            hidden: this.caseField.hidden,
            value: item.value,
            label: null,
            acls: this.caseField.acls
        });
    };
    WriteCollectionFieldComponent.prototype.buildControlRegistrer = function (id, index) {
        var _this = this;
        return function (control) {
            if (_this.formArray.at(index)) {
                return _this.formArray.at(index).get('value');
            }
            _this.formValidatorsService.addValidators(_this.caseField, control);
            _this.formArray.push(new FormGroup({
                id: new FormControl(id),
                value: control
            }));
            return control;
        };
    };
    WriteCollectionFieldComponent.prototype.buildIdPrefix = function (index) {
        if ('Complex' === this.caseField.field_type.collection_field_type.type) {
            return this.idPrefix + this.caseField.id + '_' + index + '_';
        }
        else {
            return this.idPrefix + this.caseField.id + '_';
        }
    };
    WriteCollectionFieldComponent.prototype.addItem = function (doScroll) {
        var _this = this;
        // Manually resetting errors is required to prevent `ExpressionChangedAfterItHasBeenCheckedError`
        this.formArray.setErrors(null);
        this.caseField.value.push({ value: null });
        var lastIndex = this.caseField.value.length - 1;
        // Timeout is required for the collection item to be rendered before it can be scrolled to or focused.
        if (doScroll) {
            setTimeout(function () {
                _this.scrollToService.scrollTo({
                    target: _this.buildIdPrefix(lastIndex) + lastIndex,
                    duration: 1000,
                    offset: -150,
                })
                    .pipe(finalize(function () { return _this.focusLastItem(); }))
                    .subscribe(null, console.error);
            });
        }
        else {
            setTimeout(function () { return _this.focusLastItem(); });
        }
    };
    WriteCollectionFieldComponent.prototype.focusLastItem = function () {
        if (this.items.last.nativeElement.querySelector('.form-control')) {
            this.items.last.nativeElement.querySelector('.form-control').focus();
        }
    };
    WriteCollectionFieldComponent.prototype.removeItem = function (index) {
        this.caseField.value.splice(index, 1);
        this.formArray.removeAt(index);
    };
    WriteCollectionFieldComponent.prototype.itemLabel = function (index) {
        var displayIndex = index + 1;
        return index ? this.caseField.label + " " + displayIndex : this.caseField.label;
    };
    WriteCollectionFieldComponent.prototype.isNotAuthorisedToCreate = function () {
        var _this = this;
        if (this.isExpanded) {
            return false;
        }
        return !this.profile.user.idam.roles.find(function (role) { return _this.hasCreateAccess(role); });
    };
    WriteCollectionFieldComponent.prototype.hasCreateAccess = function (role) {
        return !!this.caseField.acls.find(function (acl) { return acl.role === role && acl.create === true; });
    };
    WriteCollectionFieldComponent.prototype.isNotAuthorisedToUpdate = function (index) {
        var _this = this;
        if (this.isExpanded) {
            return false;
        }
        var id = false;
        if (this.formArray.at(index)) {
            id = this.formArray.at(index).get('id').value;
        }
        return !!id && !this.profile.user.idam.roles.find(function (role) { return _this.hasUpdateAccess(role); });
    };
    WriteCollectionFieldComponent.prototype.hasUpdateAccess = function (role) {
        return !!this.caseField.acls.find(function (acl) { return acl.role === role && acl.update === true; });
    };
    WriteCollectionFieldComponent.prototype.isNotAuthorisedToDelete = function (index) {
        var _this = this;
        if (this.isExpanded) {
            return false;
        }
        var id = false;
        if (this.formArray.at(index)) {
            id = this.formArray.at(index).get('id').value;
        }
        return !!id && !this.profile.user.idam.roles.find(function (role) { return _this.hasDeleteAccess(role); });
    };
    WriteCollectionFieldComponent.prototype.hasDeleteAccess = function (role) {
        return !!this.caseField.acls.find(function (acl) { return acl.role === role && acl.delete === true; });
    };
    WriteCollectionFieldComponent.prototype.openModal = function (i) {
        var _this = this;
        var dialogConfig = new MatDialogConfig();
        dialogConfig.disableClose = true;
        dialogConfig.autoFocus = true;
        dialogConfig.ariaLabel = 'Label';
        dialogConfig.height = '220px';
        dialogConfig.width = '550px';
        dialogConfig.panelClass = 'dialog';
        dialogConfig.closeOnNavigation = false;
        dialogConfig.position = {
            top: window.innerHeight / 2 - 110 + 'px', left: window.innerWidth / 2 - 275 + 'px'
        };
        var dialogRef = this.dialog.open(RemoveDialogComponent, dialogConfig);
        dialogRef.afterClosed().subscribe(function (result) {
            if (result === 'Remove') {
                _this.removeItem(i);
            }
        });
    };
    __decorate([
        Input(),
        __metadata("design:type", Array)
    ], WriteCollectionFieldComponent.prototype, "caseFields", void 0);
    __decorate([
        Input(),
        __metadata("design:type", FormGroup)
    ], WriteCollectionFieldComponent.prototype, "formGroup", void 0);
    __decorate([
        ViewChildren('collectionItem'),
        __metadata("design:type", QueryList)
    ], WriteCollectionFieldComponent.prototype, "items", void 0);
    WriteCollectionFieldComponent = __decorate([
        Component({
            selector: 'ccd-write-collection-field',
            template: "\n    <div class=\"form-group\" [id]=\"id()\">\n\n      <div class=\"panel panel-border-wide\">\n\n        <h2 class=\"heading-h2\">\n          {{caseField | ccdFieldLabel}}\n        </h2>\n        <button class=\"button\" type=\"button\" (click)=\"addItem(true)\" [disabled]=\"isNotAuthorisedToCreate()\" *ngIf=\"!caseField.isDisplayModeFixed()\">Add new</button>\n        <h2 class=\"heading-h2 error-spacing\">\n          <span *ngIf=\"caseField.hint_text\" class=\"form-hint\">{{caseField.hint_text}}</span>\n          <span *ngIf=\"formArray.errors\" class=\"error-message\">{{formArray.errors | ccdFirstError}}</span>\n        </h2>\n\n        <div class=\"form-group\" *ngIf=\"caseField.value && caseField.value.length\">\n\n          <div class=\"form-group\" *ngFor=\"let item of caseField.value; let i = index\" #collectionItem>\n            <div class=\"collection-title\">\n              <div class=\"float-left\">\n                <label [for]=\"buildIdPrefix(i) + i\"><h3 class=\"heading-h3\">{{itemLabel(i)}}</h3></label>\n              </div>\n              <div *ngIf=\"!caseField.isDisplayModeFixed()\" class=\"float-right\">\n                <button class=\"button button-secondary\" type=\"button\" (click)=\"openModal(i)\"\n                        [disabled]=\"isNotAuthorisedToDelete(i)\"\n                        attr.aria-label=\"Remove {{ itemLabel(i) }}\">Remove</button>\n              </div>\n            </div>\n            <ccd-field-write [caseField]=\"buildCaseField(item, i)\"\n                             [caseFields]=\"caseFields\"\n                             [caseId]=\"caseId\"\n                             [formGroup]=\"formGroup\"\n                             [registerControl]=\"buildControlRegistrer(item.id, i)\"\n                             [idPrefix]=\"buildIdPrefix(i)\"\n                             *ngIf=\"!isNotAuthorisedToUpdate(i)\">\n            </ccd-field-write>\n            <ccd-field-read [caseField]=\"buildCaseField(item, i)\"\n                            [caseFields]=\"caseFields\"\n                            [formGroup]=\"formGroup\"\n                            [context]=\"context\"\n                            *ngIf=\"isNotAuthorisedToUpdate(i)\">\n            </ccd-field-read>\n          </div>\n\n        </div>\n\n        <button class=\"button\" type=\"button\" (click)=\"addItem()\" [disabled]=\"isNotAuthorisedToCreate()\" *ngIf=\"caseField.value && caseField.value.length && !caseField.isDisplayModeFixed()\">Add new</button>\n\n      </div>\n\n    </div>\n  ",
            styles: ["\n    .collection-table-expanded-view{width:160%}.collection-field-table tr:first-child>td{padding-top:0}.collection-field-table tr:last-child>td{border-bottom:none}.collection-field-table td.collection-actions{width:1px;white-space:nowrap}.error-spacing{margin-top:10px}.collection-title{height:51px}.float-left{float:left;padding-top:8px}.float-right{float:right}.complex-panel{margin:13px 0px;border:1px solid #bfc1c3}.complex-panel .complex-panel-title{background-color:#dee0e2;padding:5px;border-bottom:1px solid #bfc1c3;font-weight:bold;display:block;color:#0b0c0c;padding-bottom:2px;font-family:\"nta\",Arial,sans-serif;font-weight:700;text-transform:none;font-size:16px;line-height:1.25}@media (min-width: 641px){.complex-panel .complex-panel-title{font-size:19px;line-height:1.31579}}.complex-panel .complex-panel-table>tbody>tr>th{vertical-align:top}.complex-panel .complex-panel-table>tbody>tr:last-child>th,.complex-panel .complex-panel-table>tbody>tr:last-child>td{border-bottom:none}.complex-panel .complex-panel-simple-field th{padding-left:5px;width:295px}.complex-panel .complex-panel-compound-field td{padding:5px}\n  "]
        }),
        __metadata("design:paramtypes", [FormValidatorsService,
            MatDialog,
            ScrollToService,
            ProfileNotifier])
    ], WriteCollectionFieldComponent);
    return WriteCollectionFieldComponent;
}(AbstractFieldWriteComponent));
export { WriteCollectionFieldComponent };
//# sourceMappingURL=write-collection-field.component.js.map