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 { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService } from '../../../services/alert/alert.service';
import { RouterHelperService } from '../../../services/router/router-helper.service';
import { WizardFactoryService } from './wizard-factory.service';
import { ShowCondition } from '../../../directives/conditional-show/domain/conditional-show.model';
import { EventTriggerService } from './event-trigger.service';
import { first } from 'rxjs/operators';
var CaseEditWizardGuard = /** @class */ (function () {
    function CaseEditWizardGuard(router, routerHelper, wizardFactory, alertService, eventTriggerService) {
        this.router = router;
        this.routerHelper = routerHelper;
        this.wizardFactory = wizardFactory;
        this.alertService = alertService;
        this.eventTriggerService = eventTriggerService;
    }
    CaseEditWizardGuard_1 = CaseEditWizardGuard;
    CaseEditWizardGuard.prototype.resolve = function (route) {
        var _this = this;
        this.eventTriggerService.eventTriggerSource.asObservable().pipe(first()).subscribe(function (eventTrigger) {
            _this.processEventTrigger(route, eventTrigger);
        });
        if (route.parent.data.eventTrigger) {
            this.eventTriggerService.announceEventTrigger(route.parent.data.eventTrigger);
        }
        return Promise.resolve(true);
    };
    CaseEditWizardGuard.prototype.processEventTrigger = function (route, eventTrigger) {
        var _this = this;
        var _a;
        if (((_a = route.routeConfig) === null || _a === void 0 ? void 0 : _a.path) === CaseEditWizardGuard_1.SUBMIT_PAGE_ID) {
            return this.processSubmitTrigger(route, eventTrigger);
        }
        if (!eventTrigger.hasFields() || !eventTrigger.hasPages()) {
            this.goToSubmit(route);
            return Promise.resolve(false);
        }
        var wizard = this.createWizard(eventTrigger);
        var canShowPredicate = this.createCanShowPredicate(eventTrigger);
        if (!route.params['page']) {
            this.goToFirst(wizard, canShowPredicate, route);
            return Promise.resolve(false);
        }
        var pageId = route.params['page'];
        if (!wizard.hasPage(pageId)) {
            this.goToFirst(wizard, canShowPredicate, route)
                .then(function () {
                _this.alertService.error("No page could be found for '" + pageId + "'");
            });
            return Promise.resolve(false);
        }
        if (this.isPageReloadedAndNotFirstPage(wizard, canShowPredicate, pageId)) {
            return this.goToFirst(wizard, canShowPredicate, route)
                .then(function () { return false; });
        }
        return Promise.resolve(true);
    };
    CaseEditWizardGuard.prototype.processSubmitTrigger = function (route, eventTrigger) {
        if (this.isPageReloaded()) {
            var wizard = this.createWizard(eventTrigger);
            var canShowPredicate = this.createCanShowPredicate(eventTrigger);
            var firstPage = wizard.firstPage(canShowPredicate);
            if (firstPage) {
                return this.goToFirst(wizard, canShowPredicate, route)
                    .then(function () { return false; });
            }
        }
        return Promise.resolve(true);
    };
    CaseEditWizardGuard.prototype.createWizard = function (eventTrigger) {
        return this.wizardFactory.create(eventTrigger);
    };
    CaseEditWizardGuard.prototype.createCanShowPredicate = function (eventTrigger) {
        var currentState = this.buildState(eventTrigger.case_fields);
        return function (page) {
            return new ShowCondition(page.show_condition).match(currentState);
        };
    };
    CaseEditWizardGuard.prototype.isPageReloadedAndNotFirstPage = function (wizard, canShowPredicate, pageId) {
        return this.isPageReloaded() && !this.isFirstPage(pageId, wizard, canShowPredicate);
    };
    CaseEditWizardGuard.prototype.isPageReloaded = function () {
        // 'router.navigated' returns true if at least one navigation event has occurred, false otherwise. If the page is
        // reloaded, 'navigated' will return false.
        return !this.router.navigated;
    };
    CaseEditWizardGuard.prototype.isFirstPage = function (pageId, wizard, canShowPredicate) {
        var id = (wizard.firstPage(canShowPredicate) || {}).id;
        return id && id === pageId;
    };
    CaseEditWizardGuard.prototype.goToFirst = function (wizard, canShowPredicate, route) {
        var firstPage = wizard.firstPage(canShowPredicate);
        // If there’s no specific wizard page called, it makes another navigation to either the first page available or to the submit page
        // TODO should find a way to navigate to target page without going through the whole loop (and make a second call to BE) again
        return this.router.navigate(__spreadArrays(this.parentUrlSegments(route), [firstPage ? firstPage.id : 'submit']), { queryParams: route.queryParams });
    };
    CaseEditWizardGuard.prototype.goToSubmit = function (route) {
        return this.router.navigate(__spreadArrays(this.parentUrlSegments(route), ['submit']));
    };
    CaseEditWizardGuard.prototype.buildState = function (caseFields) {
        var state = {};
        caseFields.forEach(function (field) {
            state[field.id] = field.value;
        });
        return state;
    };
    CaseEditWizardGuard.prototype.parentUrlSegments = function (route) {
        return this.routerHelper.getUrlSegmentsFromRoot(route.parent);
    };
    var CaseEditWizardGuard_1;
    CaseEditWizardGuard.SUBMIT_PAGE_ID = 'submit';
    CaseEditWizardGuard = CaseEditWizardGuard_1 = __decorate([
        Injectable(),
        __metadata("design:paramtypes", [Router,
            RouterHelperService,
            WizardFactoryService,
            AlertService,
            EventTriggerService])
    ], CaseEditWizardGuard);
    return CaseEditWizardGuard;
}());
export { CaseEditWizardGuard };
//# sourceMappingURL=case-edit-wizard.guard.js.map