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, NgZone } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DisplayMode } from '../../domain/activity/activity.model';
import { ActivityPollingService } from '../../services/activity/activity.polling.service';
import { Subject } from 'rxjs';
import { ShowCondition } from '../../directives/conditional-show/domain';
import { Draft, DRAFT_QUERY_PARAM } from '../../domain';
import { OrderService } from '../../services/order';
import { CaseViewTrigger } from '../../domain/case-view';
import { DeleteOrCancelDialogComponent } from '../../components/dialogs';
import { AlertService } from '../../services/alert';
import { DraftService } from '../../services/draft';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { CaseService } from '../case-editor';
var CaseViewerComponent = /** @class */ (function () {
    function CaseViewerComponent(ngZone, route, router, orderService, activityPollingService, dialog, alertService, draftService, caseService) {
        this.ngZone = ngZone;
        this.route = route;
        this.router = router;
        this.orderService = orderService;
        this.activityPollingService = activityPollingService;
        this.dialog = dialog;
        this.alertService = alertService;
        this.draftService = draftService;
        this.caseService = caseService;
        this.hasPrint = true;
        this.hasEventSelector = true;
        this.BANNER = DisplayMode.BANNER;
        this.triggerTextStart = CaseViewerComponent_1.TRIGGER_TEXT_START;
        this.triggerTextIgnoreWarnings = CaseViewerComponent_1.TRIGGER_TEXT_CONTINUE;
        this.triggerText = CaseViewerComponent_1.TRIGGER_TEXT_START;
        this.ignoreWarning = false;
        this.callbackErrorsSubject = new Subject();
    }
    CaseViewerComponent_1 = CaseViewerComponent;
    CaseViewerComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.initDialog();
        if (!this.route.snapshot.data.case) {
            this.caseService.caseView.subscribe(function (caseDetails) {
                _this.caseDetails = caseDetails;
                _this.init();
            });
        }
        else {
            this.caseDetails = this.route.snapshot.data.case;
            this.init();
        }
    };
    CaseViewerComponent.prototype.isPrintEnabled = function () {
        return this.caseDetails.case_type.printEnabled;
    };
    CaseViewerComponent.prototype.ngOnDestroy = function () {
        if (this.activityPollingService.isEnabled) {
            this.subscription.unsubscribe();
        }
    };
    CaseViewerComponent.prototype.postViewActivity = function () {
        return this.activityPollingService.postViewActivity(this.caseDetails.case_id);
    };
    CaseViewerComponent.prototype.clearErrorsAndWarnings = function () {
        this.resetErrors();
        this.ignoreWarning = false;
        this.triggerText = CaseViewerComponent_1.TRIGGER_TEXT_START;
    };
    CaseViewerComponent.prototype.applyTrigger = function (trigger) {
        var _this = this;
        this.error = null;
        var theQueryParams = {};
        if (this.ignoreWarning) {
            theQueryParams['ignoreWarning'] = this.ignoreWarning;
        }
        // we may need to take care of different triggers in the future
        if (trigger.id === CaseViewTrigger.DELETE) {
            var dialogRef = this.dialog.open(DeleteOrCancelDialogComponent, this.dialogConfig);
            dialogRef.afterClosed().subscribe(function (result) {
                if (result === 'Delete') {
                    _this.draftService.deleteDraft(_this.caseDetails.case_id)
                        .subscribe(function (_) {
                        return _this.router.navigate(['list/case'])
                            .then(function () {
                            _this.alertService.setPreserveAlerts(true);
                            _this.alertService.success("The draft has been successfully deleted");
                        });
                    }, function (_) {
                        return _this.router.navigate(['list/case']);
                    });
                }
            });
        }
        else if (this.isDraft() && trigger.id !== CaseViewTrigger.DELETE) {
            theQueryParams[DRAFT_QUERY_PARAM] = this.caseDetails.case_id;
            theQueryParams[CaseViewerComponent_1.ORIGIN_QUERY_PARAM] = 'viewDraft';
            return this.router.navigate(['create/case',
                this.caseDetails.case_type.jurisdiction.id,
                this.caseDetails.case_type.id,
                trigger.id], { queryParams: theQueryParams }).catch(function (error) {
                _this.handleError(error, trigger);
            });
        }
        else {
            return this.router.navigate(['trigger', trigger.id], {
                queryParams: theQueryParams,
                relativeTo: this.route
            }).catch(function (error) {
                _this.handleError(error, trigger);
            });
        }
    };
    CaseViewerComponent.prototype.isDataLoaded = function () {
        return this.caseDetails ? true : false;
    };
    CaseViewerComponent.prototype.hasTabsPresent = function () {
        return this.sortedTabs.length > 0;
    };
    CaseViewerComponent.prototype.callbackErrorsNotify = function (callbackErrorsContext) {
        this.ignoreWarning = callbackErrorsContext.ignore_warning;
        this.triggerText = callbackErrorsContext.trigger_text;
    };
    CaseViewerComponent.prototype.isDraft = function () {
        return Draft.isDraft(this.caseDetails.case_id);
    };
    CaseViewerComponent.prototype.isTriggerButtonDisabled = function () {
        return (this.error
            && this.error.callbackErrors
            && this.error.callbackErrors.length)
            || (this.error
                && this.error.details
                && this.error.details.field_errors
                && this.error.details.field_errors.length);
    };
    CaseViewerComponent.prototype.init = function () {
        var _this = this;
        // Clone and sort tabs array
        this.sortedTabs = this.orderService.sort(this.caseDetails.tabs);
        this.caseFields = this.getTabFields();
        this.sortedTabs = this.sortTabFieldsAndFilterTabs(this.sortedTabs);
        if (this.activityPollingService.isEnabled) {
            this.ngZone.runOutsideAngular(function () {
                _this.subscription = _this.postViewActivity().subscribe(function (_resolved) {
                    // console.log('Posted VIEW activity and result is: ' + JSON.stringify(_resolved));
                });
            });
        }
        if (this.caseDetails.triggers && this.error) {
            this.resetErrors();
        }
    };
    CaseViewerComponent.prototype.sortTabFieldsAndFilterTabs = function (tabs) {
        var _this = this;
        return tabs
            .map(function (tab) { return Object.assign({}, tab, { fields: _this.orderService.sort(tab.fields) }); })
            .filter(function (tab) { return new ShowCondition(tab.show_condition).matchByContextFields(_this.caseFields); });
    };
    CaseViewerComponent.prototype.getTabFields = function () {
        var caseDataFields = this.sortedTabs.reduce(function (acc, tab) {
            return acc.concat(tab.fields);
        }, []);
        return caseDataFields.concat(this.caseDetails.metadataFields);
    };
    CaseViewerComponent.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'
        };
    };
    CaseViewerComponent.prototype.handleError = function (error, trigger) {
        if (error.status !== 401 && error.status !== 403) {
            console.log('error during triggering event:', trigger.id);
            console.log(error);
            this.callbackErrorsSubject.next(error);
            if (this.hasInvalidData(error)) {
                this.error = error;
            }
        }
    };
    CaseViewerComponent.prototype.hasInvalidData = function (error) {
        return error
            && error.details
            && error.details.field_errors
            && error.details.field_errors.length;
    };
    CaseViewerComponent.prototype.resetErrors = function () {
        this.error = null;
        this.callbackErrorsSubject.next(null);
        this.alertService.clear();
    };
    var CaseViewerComponent_1;
    CaseViewerComponent.ORIGIN_QUERY_PARAM = 'origin';
    CaseViewerComponent.TRIGGER_TEXT_START = 'Go';
    CaseViewerComponent.TRIGGER_TEXT_CONTINUE = 'Ignore Warning and Go';
    __decorate([
        Input(),
        __metadata("design:type", Object)
    ], CaseViewerComponent.prototype, "hasPrint", void 0);
    __decorate([
        Input(),
        __metadata("design:type", Object)
    ], CaseViewerComponent.prototype, "hasEventSelector", void 0);
    CaseViewerComponent = CaseViewerComponent_1 = __decorate([
        Component({
            selector: 'ccd-case-viewer',
            template: "\n    <div *ngIf=\"isDataLoaded()\">\n      <div *ngIf=\"error\" class=\"error-summary\" role=\"group\" aria-labelledby=\"edit-case-event_error-summary-heading\" tabindex=\"-1\">\n        <h2 class=\"heading-h2 error-summary-heading\" id=\"edit-case-event_error-summary-heading\">\n          The callback data failed validation\n        </h2>\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\">\n            {{fieldError.message}}\n          </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      <ccd-activity [caseId]=\"caseDetails.case_id\" [displayMode]=\"BANNER\"></ccd-activity>\n      <div class=\"grid-row\">\n        <div class=\"column-one-half\">\n          <ccd-case-header [caseDetails]=\"caseDetails\"></ccd-case-header>\n          <div class=\"case-viewer-controls\" *ngIf=\"hasPrint && !isDraft() && isPrintEnabled()\">\n            <a id=\"case-viewer-control-print\" routerLink=\"print\" class=\"button button-secondary\">Print</a>\n          </div>\n        </div>\n        <div *ngIf=\"hasEventSelector\" class=\"column-one-half\">\n          <ccd-event-trigger [isDisabled]=\"isTriggerButtonDisabled()\" [triggers]=\"caseDetails.triggers\" [triggerText]=\"triggerText\" (onTriggerChange)=\"clearErrorsAndWarnings()\" (onTriggerSubmit)=\"applyTrigger($event)\"></ccd-event-trigger>\n        </div>\n      </div>\n      <div class=\"grid-row\">\n        <div class=\"column-full\">\n          <ng-container *ngIf=\"hasTabsPresent()\">\n            <cut-tabs>\n              <cut-tab *ngFor=\"let tab of sortedTabs; let curIdx=index\" [id]=\"tab.id\" [title]=\"tab.label\" [selected]=\"curIdx==0\">\n                <table [class]=\"tab.id\">\n                  <tbody>\n                  <ng-container *ngFor=\"let field of tab.fields\">\n                    <div ccdConditionalShow ccdLabelSubstitutor [caseField]=\"field\" [contextFields]=\"caseFields\">\n                      <ng-container [ngSwitch]=\"!(field | ccdIsCompound)\">\n                        <tr *ngSwitchCase=\"true\">\n                          <th>\n                            <div class=\"case-viewer-label text-16\">{{field.label}}</div>\n                          </th>\n                          <td><span class=\"text-16\"><ccd-field-read [caseField]=\"field\" [caseReference]=\"caseDetails.case_id\"></ccd-field-read></span></td>\n                        </tr>\n                        <tr *ngSwitchCase=\"false\" class=\"compound-field\">\n                          <th><span class=\"text-16\"><ccd-field-read [caseField]=\"field\" [caseReference]=\"caseDetails.case_id\"></ccd-field-read></span></th>\n                        </tr>\n                      </ng-container>\n                    </div>\n                  </ng-container>\n                  </tbody>\n                </table>\n              </cut-tab>\n            </cut-tabs>\n          </ng-container>\n        </div>\n      </div>\n    </div>\n  ",
            styles: ["\n    th{width:1%;white-space:nowrap;vertical-align:top}.compound-field th{padding:0}.case-viewer-controls{margin-top:47px;margin-bottom:20px}ccd-case-header{float:left;margin-right:10px}ccd-event-trigger{float:right}.case-viewer-label{min-width:300px;white-space:normal}.markdown h3{margin-bottom:0px}\n  "]
        }),
        __metadata("design:paramtypes", [NgZone,
            ActivatedRoute,
            Router,
            OrderService,
            ActivityPollingService,
            MatDialog,
            AlertService,
            DraftService,
            CaseService])
    ], CaseViewerComponent);
    return CaseViewerComponent;
}());
export { CaseViewerComponent };
//# sourceMappingURL=case-viewer.component.js.map