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);
};
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 { ChangeDetectorRef, Component } from '@angular/core';
import { FormArray } from '@angular/forms';
import { CaseEditComponent } from '../case-edit/case-edit.component';
import { ActivatedRoute } from '@angular/router';
import { Subject } from 'rxjs';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { FormValueService } from '../../../services/form/form-value.service';
import { PageValidationService } from '../services/page-validation.service';
import { SaveOrDiscardDialogComponent } from '../../dialogs/save-or-discard-dialog';
import { FormErrorService } from '../../../services/form/form-error.service';
import { DRAFT_PREFIX } from '../../../domain/draft.model';
import { FieldsUtils } from '../../../services/fields';
import { WindowService } from '../../../services';
var CaseEditPageComponent = /** @class */ (function () {
    function CaseEditPageComponent(caseEdit, route, formValueService, formErrorService, cdRef, pageValidationService, dialog, windowService) {
        this.caseEdit = caseEdit;
        this.route = route;
        this.formValueService = formValueService;
        this.formErrorService = formErrorService;
        this.cdRef = cdRef;
        this.pageValidationService = pageValidationService;
        this.dialog = dialog;
        this.windowService = windowService;
        this.callbackErrorsSubject = new Subject();
        this.ignoreWarning = false;
        this.triggerTextStart = CaseEditPageComponent_1.TRIGGER_TEXT_START;
        this.triggerTextIgnoreWarnings = CaseEditPageComponent_1.TRIGGER_TEXT_CONTINUE;
        this.isSubmitting = false;
        this.formValuesChanged = false;
        this.pageChangeSubject = new Subject();
    }
    CaseEditPageComponent_1 = CaseEditPageComponent;
    CaseEditPageComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.initDialog();
        this.eventTrigger = this.caseEdit.eventTrigger;
        this.editForm = this.caseEdit.form;
        this.wizard = this.caseEdit.wizard;
        this.caseFields = this.getCaseFields();
        this.triggerText = this.getTriggerText();
        this.route.params.subscribe(function (params) {
            var pageId = params['page'];
            if (!_this.currentPage || pageId !== _this.currentPage.id) {
                var page = _this.caseEdit.getPage(pageId);
                if (page) {
                    _this.currentPage = page;
                }
                else {
                    if (_this.currentPage) {
                        return _this.next();
                    }
                    else {
                        return _this.first();
                    }
                }
            }
        });
        if (document.getElementById('main-content')) {
            document.getElementById('main-content').focus();
        }
    };
    CaseEditPageComponent.prototype.ngAfterViewChecked = function () {
        this.cdRef.detectChanges();
    };
    CaseEditPageComponent.prototype.applyValuesChanged = function (valuesChanged) {
        this.formValuesChanged = valuesChanged;
    };
    CaseEditPageComponent.prototype.initDialog = function () {
        this.dialogConfig = new MatDialogConfig();
        this.dialogConfig.disableClose = true;
        this.dialogConfig.autoFocus = true;
        this.dialogConfig.ariaLabel = 'Label';
        this.dialogConfig.height = '245px';
        this.dialogConfig.width = '550px';
        this.dialogConfig.panelClass = 'dialog';
        this.dialogConfig.closeOnNavigation = false;
        this.dialogConfig.position = {
            top: window.innerHeight / 2 - 120 + 'px', left: window.innerWidth / 2 - 275 + 'px'
        };
    };
    CaseEditPageComponent.prototype.first = function () {
        return this.caseEdit.first();
    };
    CaseEditPageComponent.prototype.currentPageIsNotValid = function () {
        return !this.pageValidationService.isPageValid(this.currentPage, this.editForm);
    };
    CaseEditPageComponent.prototype.submit = function () {
        var _this = this;
        if (!this.isSubmitting) {
            this.isSubmitting = true;
            this.error = null;
            var pageFormFields = this.formValueService.filterCurrentPageFields(this.currentPage.case_fields, this.editForm.value);
            this.formValueService.sanitiseDynamicLists(this.currentPage.case_fields, pageFormFields);
            var caseEventData = this.formValueService.sanitise(pageFormFields);
            caseEventData.event_token = this.eventTrigger.event_token;
            caseEventData.ignore_warning = this.ignoreWarning;
            // use a temporary object to sanitise dynamic lists
            var tmpData = { data: this.editForm.value.data };
            this.formValueService.sanitiseDynamicLists(this.currentPage.case_fields, tmpData);
            caseEventData.event_data = tmpData.data;
            if (this.caseEdit.caseDetails) {
                caseEventData.case_reference = this.caseEdit.caseDetails.case_id;
            }
            this.caseEdit.validate(caseEventData, this.currentPage.id)
                .subscribe(function (jsonData) {
                if (jsonData) {
                    _this.updateFormData(jsonData);
                }
                _this.saveDraft();
                _this.next();
            }, function (error) { return _this.handleError(error); });
            this.windowService.scrollToTop();
        }
        if (document.getElementById('main-content')) {
            document.getElementById('main-content').focus();
        }
    };
    CaseEditPageComponent.prototype.updateFormData = function (jsonData) {
        for (var _i = 0, _a = Object.keys(jsonData.data); _i < _a.length; _i++) {
            var caseFieldId = _a[_i];
            if (this.pageWithFieldExists(caseFieldId)) {
                this.updateEventTriggerCaseFields(caseFieldId, jsonData, this.caseEdit.eventTrigger);
                this.updateFormControlsValue(this.editForm, caseFieldId, jsonData.data[caseFieldId]);
            }
        }
    };
    // we do the check, becasue the data comes from the external source
    CaseEditPageComponent.prototype.pageWithFieldExists = function (caseFieldId) {
        return this.wizard.findWizardPage(caseFieldId);
    };
    CaseEditPageComponent.prototype.updateEventTriggerCaseFields = function (caseFieldId, jsonData, eventTrigger) {
        if (eventTrigger.case_fields) {
            eventTrigger.case_fields
                .filter(function (element) { return element.id === caseFieldId; })
                .forEach(function (element) { return element.value = jsonData.data[caseFieldId]; });
        }
    };
    CaseEditPageComponent.prototype.updateFormControlsValue = function (formGroup, caseFieldId, value) {
        var theControl = formGroup.controls['data'].get(caseFieldId);
        if (theControl && theControl instanceof FormArray) {
            theControl.patchValue(value);
            var numControls = theControl.length;
            if (value.length < numControls) {
                for (var i = 1; i <= numControls - value.length; i++) {
                    theControl.removeAt(numControls - i);
                }
            }
        }
        else if (theControl) {
            theControl.patchValue(value);
        }
    };
    CaseEditPageComponent.prototype.callbackErrorsNotify = function (errorContext) {
        this.ignoreWarning = errorContext.ignore_warning;
        this.triggerText = errorContext.trigger_text;
    };
    CaseEditPageComponent.prototype.next = function () {
        this.resetErrors();
        this.isSubmitting = false;
        this.formValuesChanged = false;
        this.pageChangeSubject.next(true);
        return this.caseEdit.next(this.currentPage.id);
    };
    CaseEditPageComponent.prototype.previous = function () {
        this.resetErrors();
        this.saveDraft();
        this.formValuesChanged = false;
        this.pageChangeSubject.next(true);
        return this.caseEdit.previous(this.currentPage.id);
    };
    CaseEditPageComponent.prototype.hasPrevious = function () {
        return this.caseEdit.hasPrevious(this.currentPage.id);
    };
    CaseEditPageComponent.prototype.cancel = function () {
        var _this = this;
        if (this.eventTrigger.can_save_draft) {
            if (this.formValuesChanged) {
                var dialogRef = this.dialog.open(SaveOrDiscardDialogComponent, this.dialogConfig);
                dialogRef.afterClosed().subscribe(function (result) {
                    if (result === 'Discard') {
                        _this.discard();
                    }
                    else if (result === 'Save') {
                        var draftCaseEventData = _this.formValueService.sanitise(_this.editForm.value);
                        if (_this.route.snapshot.queryParamMap.get(CaseEditComponent.ORIGIN_QUERY_PARAM) === 'viewDraft') {
                            _this.caseEdit.cancelled.emit({ status: CaseEditPageComponent_1.RESUMED_FORM_SAVE, data: draftCaseEventData });
                        }
                        else {
                            _this.caseEdit.cancelled.emit({ status: CaseEditPageComponent_1.NEW_FORM_SAVE, data: draftCaseEventData });
                        }
                    }
                });
            }
            else {
                this.discard();
            }
        }
        else {
            this.caseEdit.cancelled.emit();
        }
    };
    CaseEditPageComponent.prototype.discard = function () {
        if (this.route.snapshot.queryParamMap.get(CaseEditComponent.ORIGIN_QUERY_PARAM) === 'viewDraft') {
            this.caseEdit.cancelled.emit({ status: CaseEditPageComponent_1.RESUMED_FORM_DISCARD });
        }
        else {
            this.caseEdit.cancelled.emit({ status: CaseEditPageComponent_1.NEW_FORM_DISCARD });
        }
    };
    CaseEditPageComponent.prototype.submitting = function () {
        return this.isSubmitting;
    };
    CaseEditPageComponent.prototype.handleError = function (error) {
        this.isSubmitting = false;
        this.error = error;
        this.callbackErrorsSubject.next(this.error);
        if (this.error.details) {
            this.formErrorService
                .mapFieldErrors(this.error.details.field_errors, this.editForm.controls['data'], 'validation');
        }
    };
    CaseEditPageComponent.prototype.resetErrors = function () {
        this.error = null;
        this.ignoreWarning = false;
        this.triggerText = this.getTriggerText();
        this.callbackErrorsSubject.next(null);
    };
    CaseEditPageComponent.prototype.getCaseId = function () {
        return (this.caseEdit.caseDetails ? this.caseEdit.caseDetails.case_id : '');
    };
    CaseEditPageComponent.prototype.saveDraft = function () {
        var _this = this;
        if (this.eventTrigger.can_save_draft) {
            var draftCaseEventData = this.formValueService.sanitise(this.editForm.value);
            draftCaseEventData.event_token = this.eventTrigger.event_token;
            draftCaseEventData.ignore_warning = this.ignoreWarning;
            this.caseEdit.saveDraft(draftCaseEventData).subscribe(function (draft) { return _this.eventTrigger.case_id = DRAFT_PREFIX + draft.id; }, function (error) { return _this.handleError(error); });
        }
    };
    CaseEditPageComponent.prototype.getCancelText = function () {
        if (this.eventTrigger.can_save_draft) {
            return 'Return to case list';
        }
        else {
            return 'Cancel';
        }
    };
    CaseEditPageComponent.prototype.getTriggerText = function () {
        if (this.eventTrigger && this.eventTrigger.can_save_draft) {
            return CaseEditPageComponent_1.TRIGGER_TEXT_SAVE;
        }
        else {
            return CaseEditPageComponent_1.TRIGGER_TEXT_START;
        }
    };
    CaseEditPageComponent.prototype.getCaseFields = function () {
        if (this.caseEdit.caseDetails) {
            return __spreadArrays(FieldsUtils.getCaseFields(this.caseEdit.caseDetails), this.eventTrigger.case_fields);
        }
        return this.eventTrigger.case_fields;
    };
    var CaseEditPageComponent_1;
    CaseEditPageComponent.RESUMED_FORM_DISCARD = 'RESUMED_FORM_DISCARD';
    CaseEditPageComponent.NEW_FORM_DISCARD = 'NEW_FORM_DISCARD';
    CaseEditPageComponent.NEW_FORM_SAVE = 'NEW_FORM_CHANGED_SAVE';
    CaseEditPageComponent.RESUMED_FORM_SAVE = 'RESUMED_FORM_SAVE';
    CaseEditPageComponent.TRIGGER_TEXT_START = 'Continue';
    CaseEditPageComponent.TRIGGER_TEXT_SAVE = 'Save and continue';
    CaseEditPageComponent.TRIGGER_TEXT_CONTINUE = 'Ignore Warning and Continue';
    CaseEditPageComponent = CaseEditPageComponent_1 = __decorate([
        Component({
            selector: 'ccd-case-edit-page',
            template: "\n    <!-- Current Page && Event trigger name -->\n    <h1 class=\"heading-h1\"><span *ngIf=\"currentPage && currentPage.label\">{{currentPage.label}}&nbsp;-&nbsp;</span>{{ eventTrigger.name}}</h1>\n\n    <!-- Case ID -->\n    <h2 *ngIf=\"getCaseId()\" class=\"heading-h2\">\n      #{{ getCaseId() | ccdCaseReference}}\n    </h2>\n\n    <div *ngIf=\"error\" class=\"error-summary\" role=\"group\" aria-labelledby=\"edit-case-event_error-summary-heading\" tabindex=\"-1\">\n      <h3 class=\"heading-h3 error-summary-heading\" id=\"edit-case-event_error-summary-heading\">\n        The event could not be created\n      </h3>\n      <p>{{error.message}}</p>\n      <ul *ngIf=\"error.details?.field_errors\" class=\"error-summary-list\">\n        <li *ngFor=\"let fieldError of error.details.field_errors\" class=\" ccd-error-summary-li\">{{fieldError.message}}</li>\n      </ul>\n    </div>\n    <ccd-callback-errors\n      [triggerTextContinue]=\"triggerTextStart\"\n      [triggerTextIgnore]=\"triggerTextIgnoreWarnings\"\n      [callbackErrorsSubject]=\"callbackErrorsSubject\"\n      (callbackErrorsContext)=\"callbackErrorsNotify($event)\">\n    </ccd-callback-errors>\n    <div [class]=\"currentPage.isMultiColumn() ? 'width-100' : 'width-50'\">\n      <form *ngIf=\"currentPage\" class=\"form\" [formGroup]=\"editForm\" (submit)=\"submit()\">\n        <fieldset id=\"fieldset-case-data\">\n          <!-- single column -->\n          <ccd-case-edit-form id='caseEditForm' *ngIf=\"!currentPage.isMultiColumn()\" [fields]=\"currentPage.getCol1Fields()\" [formGroup]=\"editForm.controls['data']\" [caseFields]=\"caseFields\" [pageChangeSubject]=\"pageChangeSubject\" (valuesChanged)=\"applyValuesChanged($event)\"></ccd-case-edit-form>\n          <!-- two columns -->\n          <div *ngIf=\"currentPage.isMultiColumn()\" class=\"grid-row\">\n            <div class=\"column-two-thirds rightBorderSeparator\">\n              <ccd-case-edit-form id='caseEditForm1' [fields]=\"currentPage.getCol1Fields()\" [formGroup]=\"editForm.controls['data']\" [caseFields]=\"caseFields\"></ccd-case-edit-form>\n            </div>\n            <div class=\"column-one-third\">\n              <ccd-case-edit-form id='caseEditForm2' [fields]=\"currentPage.getCol2Fields()\" [formGroup]=\"editForm.controls['data']\" [caseFields]=\"caseFields\"></ccd-case-edit-form>\n            </div>\n          </div>\n        </fieldset>\n\n        <div class=\"form-group form-group-related\">\n          <button class=\"button button-secondary\" type=\"button\" [disabled]=\"!hasPrevious()\" (click)=\"previous()\">Previous</button>\n          <button class=\"button\" type=\"submit\" [disabled]=\"currentPageIsNotValid() || submitting()\">{{triggerText}}</button>\n        </div>\n\n        <p class=\"cancel\"><a (click)=\"cancel()\" href=\"javascript:void(0)\">{{getCancelText()}}</a></p>\n\n      </form>\n    </div>\n  ",
            styles: ["\n    .rightBorderSeparator{border-right-width:4px;border-right-color:#ffcc02;border-right-style:solid}\n  "]
        }),
        __metadata("design:paramtypes", [CaseEditComponent,
            ActivatedRoute,
            FormValueService,
            FormErrorService,
            ChangeDetectorRef,
            PageValidationService,
            MatDialog,
            WindowService])
    ], CaseEditPageComponent);
    return CaseEditPageComponent;
}());
export { CaseEditPageComponent };
//# sourceMappingURL=case-edit-page.component.js.map