'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-ceff47a0.js');
const index_esm_min = require('./index.esm.min-f57d151c.js');
const index_esm_min$1 = require('./index.esm.min-1101deb1.js');
const index_esm_min$2 = require('./index.esm.min-2e158fd8.js');
const reduxStore_service = require('./redux-store.service-10b7725a.js');

const bpSdkNextButtonContainerCss = "";
const BpSdkNextButtonContainerStyle0 = bpSdkNextButtonContainerCss;

const BpSdkNextButtonContainer = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.bpAnalyticsTrack = index.createEvent(this, "bpAnalyticsTrack", 7);
        this.handleSubscriptions = () => {
            if (this.storeUnsubscribe) {
                this.storeUnsubscribe();
            }
            reduxStore_service.store.mapDispatchToProps(this, {
                saveQuestionSet: index_esm_min.an,
                updateErrors: index_esm_min.S5,
                removeActiveAnswerId: index_esm_min._8,
                switchActiveQuestionSet: index_esm_min.m8,
                pushAnswer: index_esm_min.wa,
                getEligibilityResults: index_esm_min.tf,
                setAddressValidationStatus: index_esm_min.Mh,
                setAddressValidationTriggerOverridden: index_esm_min.o6,
            });
            this.storeUnsubscribe = reduxStore_service.store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => ({
            activeQuestionSet: index_esm_min.Oe(state),
            applicationId: index_esm_min.SL(state),
            config: index_esm_min.up(state),
            answersResourceState: index_esm_min.cR(state),
            applicationFormResourceState: index_esm_min.lR(state),
            pendingProcesses: state.application.pendingProcesses,
            questionPoolResourceState: index_esm_min.dR(state),
            questionSetResourceState: index_esm_min.fR(state),
            questionSetState: index_esm_min.We(state),
            queue: state.queues.answers.queue,
            enableUserApplicationGuard: !!state.config.options.enableUserApplicationGuard,
            locked: state.application.form.locked,
            isActiveQuestionSetPendingProcess: index_esm_min.xN(state),
            isOwner: index_esm_min.MN(state),
            hasPermissionToEdit: index_esm_min.VN(state, {
                permission: index_esm_min$1.T.ApplicationForms,
                action: index_esm_min$1.O.Update,
            }),
            addressValidationStatuses: index_esm_min.ZR(state),
            addressIdsToBeValidated: index_esm_min.GR(state),
            isValidationTriggerOverridden: index_esm_min.eM(state),
            isActiveQuestionSetBeingValidated: index_esm_min.HR(state, this.activeQuestionSet),
        });
        this.activeQuestionSet = undefined;
        this.buttonDisabled = false;
        this.config = undefined;
        this.queue = undefined;
        this.shouldDisableIfIncomplete = false;
        this.answersResourceState = undefined;
        this.applicationFormResourceState = undefined;
        this.questionPoolResourceState = undefined;
        this.questionSetResourceState = undefined;
        this.questionSetState = undefined;
        this.locked = undefined;
        this.pendingProcesses = undefined;
        this.isOwner = undefined;
        this.hasPermissionToEdit = undefined;
        this.isActiveQuestionSetPendingProcess = undefined;
        this.enableUserApplicationGuard = undefined;
        this.applicationId = undefined;
        this.addressValidationStatuses = undefined;
        this.addressIdsToBeValidated = undefined;
        this.isValidationTriggerOverridden = undefined;
        this.useExternal = false;
        this.canSave = true;
        this.areResourcesReady = true;
        this.isDisabled = false;
        this.caDisabled = false;
        this.isReady = true;
        this.isLocked = false;
        this.isFirstRun = true;
        this.classes = '';
        this.isActiveQuestionSetBeingValidated = undefined;
    }
    resetState() {
        this.isReady = true;
        this.isFirstRun = true;
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-next-button-container');
        customElements.whenDefined('bp-sdk-external-next-button-container').then(() => {
            this.useExternal = true;
        });
        this.handleSubscriptions();
        this.onShouldDisableIfIncompleteChange(this.shouldDisableIfIncomplete);
        this.onAnswersResourcesStateChange(this.answersResourceState);
        this.onApplicationFormResourceStateChange(this.applicationFormResourceState);
        this.onHasPermissionToEdit(this.hasPermissionToEdit);
        this.onEnableUserApplicationGuard(this.enableUserApplicationGuard);
        this.onIsFirstRun(this.isFirstRun);
        this.onIsOwner(this.isOwner);
        this.onIsReady(this.isReady);
        this.onLocked(this.locked);
        this.onQuestionPoolResourcesStateChange(this.questionPoolResourceState);
        this.onQuestionSetResourcesStateChange(this.questionSetResourceState);
        this.onQueueChange(this.queue);
        this.onIsActiveQuestionSetPendingProcess(this.isActiveQuestionSetPendingProcess);
        this.onAddressValidationStatusChange(this.addressValidationStatuses);
    }
    onEnableUserApplicationGuard(enableUserApplicationGuard) {
        this.updateIsLocked(this.locked, this.isOwner, this.hasPermissionToEdit, enableUserApplicationGuard);
    }
    onHasPermissionToEdit(hasPermission) {
        this.updateIsLocked(this.locked, this.isOwner, hasPermission, this.enableUserApplicationGuard);
    }
    onIsOwner(isOwner) {
        this.updateIsLocked(this.locked, isOwner, this.hasPermissionToEdit, this.enableUserApplicationGuard);
    }
    onLocked(locked) {
        this.updateIsLocked(locked, this.isOwner, this.hasPermissionToEdit, this.enableUserApplicationGuard);
    }
    updateIsLocked(locked, isOwner, hasPermission, enableUserApplicationGuard) {
        this.isLocked = locked || (enableUserApplicationGuard && (!isOwner || !hasPermission));
    }
    onIsFirstRun(isFirstRun) {
        this.updateAreResourcesReady(isFirstRun, this.isReady);
    }
    onIsReady(isReady) {
        this.updateAreResourcesReady(this.isFirstRun, isReady);
    }
    updateAreResourcesReady(isFirstRun, isReady) {
        this.areResourcesReady = isFirstRun || isReady;
    }
    onAnswersResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: state,
            applicationForm: this.applicationFormResourceState,
            questionPools: this.questionPoolResourceState,
            questionSets: this.questionSetResourceState,
        });
    }
    onApplicationFormResourceStateChange(state) {
        if (this.isFirstRun && state === index_esm_min$1.d.Loaded) {
            this.isFirstRun = false;
        }
        this.isReady = this.calculateResourcesReady({
            answers: this.answersResourceState,
            applicationForm: state,
            questionPools: this.questionPoolResourceState,
            questionSets: this.questionSetResourceState,
        });
    }
    onQuestionPoolResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: this.answersResourceState,
            applicationForm: this.applicationFormResourceState,
            questionPools: state,
            questionSets: this.questionSetResourceState,
        });
    }
    onQuestionSetResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: this.answersResourceState,
            applicationForm: this.applicationFormResourceState,
            questionPools: this.questionPoolResourceState,
            questionSets: state,
        });
    }
    calculateResourcesReady(resources = {}) {
        if (!resources ||
            resources.applicationForm !== index_esm_min$1.d.Loaded ||
            resources.answers === index_esm_min$1.d.Loading ||
            resources.questionPools === index_esm_min$1.d.Loading ||
            resources.questionSets === index_esm_min$1.d.Loading) {
            return false;
        }
        return true;
    }
    onShouldDisableIfIncompleteChange(shouldDisableIfIncomplete) {
        this.updateOnDisableIfIncomplete(shouldDisableIfIncomplete, this.activeQuestionSet);
    }
    onActiveQuestionSetChange(activeQuestionSet) {
        this.updateOnDisableIfIncomplete(this.shouldDisableIfIncomplete, activeQuestionSet);
        this.disableIfCAQuestionSet(this.shouldDisableIfIncomplete, activeQuestionSet);
    }
    onQueueChange(queue) {
        this.canSave = !(queue === null || queue === void 0 ? void 0 : queue.length) && !this.isActiveQuestionSetPendingProcess;
    }
    onAddressValidationStatusChange(statuses) {
        if (statuses &&
            this.activeQuestionSet &&
            Object.values(statuses).some((status) => status === index_esm_min$1.se.PROCEED_NEXT || status === index_esm_min$1.se.VALIDATION_ERROR) &&
            !this.isValidationTriggerOverridden) {
            const filteredIds = Object.keys(statuses).filter((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
                this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
            if (filteredIds.every((id) => statuses[id] === index_esm_min$1.se.PROCEED_NEXT ||
                statuses[id] === index_esm_min$1.se.COMPLETED ||
                statuses[id] === index_esm_min$1.se.VALIDATION_ERROR)) {
                this.saveQuestionSetAndProceed();
                filteredIds
                    .filter((id) => statuses[id] === index_esm_min$1.se.PROCEED_NEXT)
                    .forEach((addressValidationId) => this.setAddressValidationStatus({ validationStatus: index_esm_min$1.se.COMPLETED, addressValidationId }));
                filteredIds
                    .filter((id) => statuses[id] === index_esm_min$1.se.VALIDATION_ERROR)
                    .forEach((addressValidationId) => this.setAddressValidationStatus({ validationStatus: index_esm_min$1.se.REQUIRED, addressValidationId }));
            }
        }
    }
    onIsActiveQuestionSetPendingProcess(isQSPending) {
        this.canSave = !isQSPending;
    }
    disableIfCAQuestionSet(shouldDisableIfIncomplete, activeQuestionSet) {
        let shouldDisable = false;
        if (shouldDisableIfIncomplete && activeQuestionSet) {
            shouldDisable = index_esm_min$2.$i(activeQuestionSet);
        }
        if (this.caDisabled !== shouldDisable) {
            this.caDisabled = shouldDisable;
        }
    }
    updateOnDisableIfIncomplete(shouldDisableIfIncomplete, activeQuestionSet) {
        this.isDisabled = shouldDisableIfIncomplete && this.isDisabledStatusByActiveQuestionSet(activeQuestionSet);
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (index.h("bp-sdk-external-next-button-container", { activeQuestionSet: this.activeQuestionSet, answersResourceState: this.answersResourceState, applicationFormResourceState: this.applicationFormResourceState, applicationId: this.applicationId, buttonDisabled: this.buttonDisabled, config: this.config, enableUserApplicationGuard: this.enableUserApplicationGuard, hasPermissionToEdit: this.hasPermissionToEdit, isOwner: this.isOwner, locked: this.locked, pendingProcesses: this.pendingProcesses, questionPoolResourceState: this.questionPoolResourceState, questionSetResourceState: this.questionSetResourceState, questionSetState: this.questionSetState, queue: this.queue, shouldDisableIfIncomplete: this.shouldDisableIfIncomplete, isActiveQuestionSetPendingProcess: this.isActiveQuestionSetPendingProcess }));
    }
    handleNavigateNext() {
        if (this.isAddressValidationRequired()) {
            this.handleValidation();
        }
        else {
            this.saveQuestionSetAndProceed();
        }
    }
    renderInternal() {
        return (index.h("bp-sdk-next-button", { buttonDisabled: !this.isNextButtonClickable() || this.isActiveQuestionSetBeingValidated, cssClasses: !this.areResourcesReady || !this.canSave ? 'loading' : 'not-loading' }));
    }
    parentQuestionSetCanSave() {
        const parentQuestionSet = this.questionSetState.parentQuestionSets.find((pqs) => pqs.id === this.activeQuestionSet.parentQuestionSetId);
        if (parentQuestionSet) {
            return this.questionSetState.list
                .filter((qs) => qs.parentQuestionSetId === parentQuestionSet.id)
                .every((qs) => index_esm_min$2.et(qs.answers));
        }
    }
    saveQuestionSetAndProceed() {
        if (this.shouldCallSaveQuestionSet()) {
            const invalidAnswers = this.activeQuestionSet.answers.filter((answer) => !index_esm_min$2.hi(answer));
            if (!invalidAnswers.length && this.isNextButtonClickable()) {
                this.removeActiveAnswerId();
                if (!this.activeQuestionSet.parentQuestionSetId) {
                    this.callSaveQuestionSet();
                }
                else {
                    if (this.parentQuestionSetCanSave()) {
                        this.callSaveQuestionSet(true);
                    }
                    else {
                        this.handleStep();
                    }
                }
            }
            else {
                invalidAnswers.forEach((answer) => {
                    this.updateErrors({ answer, errors: index_esm_min$2.Jr(answer) });
                });
                index_esm_min$2.s$();
            }
        }
        else if (this.isNextButtonClickable()) {
            this.switchActiveQuestionSet('forward');
        }
    }
    callSaveQuestionSet(useParent = false) {
        this.saveQuestionSet({
            config: this.config,
            appFormQuestionSet: this.activeQuestionSet,
            navigationDirection: 'forward',
            parentQuestionSet: useParent
                ? this.questionSetState.parentQuestionSets.find((pqs) => pqs.id === this.activeQuestionSet.parentQuestionSetId)
                : undefined,
        });
        this.bpAnalyticsTrack.emit({
            eventName: index_esm_min$1.he.QuestionSetSaved,
            eventPayload: {
                applicationFormQuestionSetId: this.activeQuestionSet.id,
                questionSetId: this.activeQuestionSet.question_set_id,
                questionSetCode: this.activeQuestionSet.question_set.code,
            },
        });
    }
    handleStep() {
        const parent = index_esm_min$2.ww(this.activeQuestionSet, this.questionSetState);
        const newValue = index_esm_min$2.Sw(this.activeQuestionSet);
        if (parent.value !== newValue) {
            this.pushAnswer(index_esm_min$2.Sa(parent, newValue));
        }
        this.getEligibilityResults({ appId: this.applicationId, config: this.config });
        this.switchActiveQuestionSet('forward');
    }
    isDisabledStatusByActiveQuestionSet(activeQuestionSet) {
        var _a;
        // If missing active question set then default to disable.
        if (!activeQuestionSet) {
            return true;
        }
        // If missing answers then default to enabled
        if (!activeQuestionSet.answers || ((_a = activeQuestionSet.answers) === null || _a === void 0 ? void 0 : _a.length) === 0) {
            return false;
        }
        // Else state determined by if all required answers are completed
        return activeQuestionSet.answers.some((answer) => !answer.is_completed && answer.required);
    }
    shouldCallSaveQuestionSet() {
        if (this.isLocked) {
            return false;
        }
        return !this.activeQuestionSet.is_completed || !!this.activeQuestionSet.parentQuestionSetId;
    }
    isNextButtonClickable() {
        return !this.buttonDisabled && this.areResourcesReady && this.canSave && !this.isDisabled && !this.caDisabled;
    }
    isAddressValidationRequired() {
        return Object.keys(this.addressValidationStatuses).some((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
            this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
    }
    handleValidation() {
        if (this.isValidationTriggerOverridden) {
            this.setAddressValidationTriggerOverridden(false);
        }
        const presentRequiredIds = this.addressIdsToBeValidated.filter((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
            this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
        if (!!presentRequiredIds.length) {
            presentRequiredIds.forEach((addressValidationId) => {
                this.setAddressValidationStatus({ validationStatus: index_esm_min$1.se.READY_TO_VALIDATE, addressValidationId });
            });
        }
        else {
            const filteredIds = Object.keys(this.addressValidationStatuses).filter((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
                this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
            if (filteredIds.every((id) => this.addressValidationStatuses[id] === index_esm_min$1.se.COMPLETED ||
                this.addressValidationStatuses[id] === index_esm_min$1.se.VALIDATION_ERROR)) {
                this.saveQuestionSetAndProceed();
            }
        }
    }
    static get watchers() { return {
        "enableUserApplicationGuard": ["onEnableUserApplicationGuard"],
        "hasPermissionToEdit": ["onHasPermissionToEdit"],
        "isOwner": ["onIsOwner"],
        "locked": ["onLocked"],
        "isFirstRun": ["onIsFirstRun"],
        "isReady": ["onIsReady"],
        "answersResourceState": ["onAnswersResourcesStateChange"],
        "applicationFormResourceState": ["onApplicationFormResourceStateChange"],
        "questionPoolResourceState": ["onQuestionPoolResourcesStateChange"],
        "questionSetResourceState": ["onQuestionSetResourcesStateChange"],
        "shouldDisableIfIncomplete": ["onShouldDisableIfIncompleteChange"],
        "activeQuestionSet": ["onActiveQuestionSetChange"],
        "queue": ["onQueueChange"],
        "addressValidationStatuses": ["onAddressValidationStatusChange"],
        "isActiveQuestionSetPendingProcess": ["onIsActiveQuestionSetPendingProcess"]
    }; }
};
BpSdkNextButtonContainer.style = BpSdkNextButtonContainerStyle0;

exports.bp_sdk_next_button_container = BpSdkNextButtonContainer;
