import { r as registerInstance, c as createEvent, h, F as Fragment, g as getElement } from './index-77a9c9e7.js';
import { a as an, S as S5, w as wa, _ as _8, y as y8, u as up, i as MN, V as VN, c as cR, l as lR, d as dR, f as fR } from './index.esm.min-db2d29e8.js';
import { T, O, h as he, d, x } from './index.esm.min-9889e78b.js';
import { h as hi, J as Jr, s as s$, b as Sa, c as $$, U as Ur, d as h1, _ as _1 } from './index.esm.min-cd800f97.js';
import { s as store } from './redux-store.service-dc54f48e.js';

const BpSdkQuestionSetContainer = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.bpAnalyticsTrack = createEvent(this, "bpAnalyticsTrack", 7);
        this.handleSubscriptions = () => {
            this.storeUnsubscribe && this.storeUnsubscribe();
            store.mapDispatchToProps(this, {
                saveQuestionSet: an,
                updateErrors: S5,
                pushAnswer: wa,
                removeActiveAnswerId: _8,
                updateActiveAnswerId: y8,
            });
            this.storeUnsubscribe = store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => {
            return {
                questionSets: state.application.questionSets,
                config: up(state),
                enableUserApplicationGuard: !!state.config.options.enableUserApplicationGuard,
                locked: state.application.form.locked,
                isOwner: MN(state),
                hasPermissionToEdit: VN(state, {
                    permission: T.ApplicationForms,
                    action: O.Update,
                }),
                pendingProcesses: state.application.pendingProcesses,
                queue: state.queues.answers.queue,
                answersResourceState: cR(state),
                applicationFormResourceState: lR(state),
                questionPoolResourceState: dR(state),
                questionSetResourceState: fR(state),
            };
        };
        this.handleSaveQuestionSet = (questionSet) => {
            const invalidAnswers = questionSet.answers.filter((answer) => !hi(answer));
            if (!invalidAnswers.length) {
                this.removeActiveAnswerId();
                this.saveQuestionSet({
                    config: this.config,
                    appFormQuestionSet: questionSet,
                    navigationDirection: 'forward',
                });
                this.bpAnalyticsTrack.emit({
                    eventName: he.QuestionSetSaved,
                    eventPayload: {
                        applicationFormQuestionSetId: questionSet.id,
                        questionSetId: questionSet.question_set_id,
                        questionSetCode: questionSet.question_set.code,
                    },
                });
            }
            else {
                invalidAnswers.forEach((answer) => {
                    this.updateErrors({ answer, errors: Jr(answer) });
                });
                s$();
            }
        };
        this.questionSets = {
            list: [],
            active: '',
            activeAnswerId: '',
            completedQuestionSetAnswerHasChanged: false,
            idOfNextActiveQuestionSetNotInState: undefined,
            parentQuestionSets: [],
        };
        this.config = undefined;
        this.answersResourceState = undefined;
        this.applicationFormResourceState = undefined;
        this.questionPoolResourceState = undefined;
        this.questionSetResourceState = undefined;
        this.locked = undefined;
        this.pendingProcesses = undefined;
        this.queue = undefined;
        this.isOwner = undefined;
        this.hasPermissionToEdit = undefined;
        this.enableUserApplicationGuard = undefined;
        this.areResourcesReady = true;
        this.useExternal = false;
        this.canSave = true;
        this.isLocked = false;
        this.isReady = true;
        this.isFirstRun = true;
        this.isLoadingApplication = false;
    }
    resetState() {
        this.isReady = true;
        this.isFirstRun = true;
        this.isLoadingApplication = false;
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-question-set-container');
        customElements.whenDefined('bp-sdk-external-question-set-container').then(() => {
            this.useExternal = true;
        });
        this.handleSubscriptions();
        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);
    }
    onQueueChange(queue) {
        this.canSave = !(queue === null || queue === void 0 ? void 0 : queue.length) && !this.doesCurrentQuestionSetHaveAPendingProcess();
    }
    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);
    }
    onPendingProcessesChange(processes) {
        this.canSave = !this.doesCurrentQuestionSetHaveAPendingProcess(processes);
    }
    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;
    }
    disconnectedCallback() {
        this.storeUnsubscribe && this.storeUnsubscribe();
    }
    onRemoveActiveAnswerRequest() {
        this.removeActiveAnswerId();
    }
    onUpdateActiveAnswerRequest({ detail }) {
        const answer = this.questionSets.list.reduce((acc, list) => acc || list.answers.find((answer) => answer.id === detail), null);
        if (answer) {
            this.updateActiveAnswerId(answer.id);
        }
    }
    onAnswersResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: state,
            applicationForm: this.applicationFormResourceState,
            questionPools: this.questionPoolResourceState,
            questionSets: this.questionSetResourceState,
        });
    }
    onApplicationFormResourceStateChange(state) {
        if (this.isFirstRun && state === d.Loaded) {
            this.isFirstRun = false;
        }
        if (state === d.Loading) {
            this.isLoadingApplication = true;
        }
        else {
            this.isLoadingApplication = 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 !== d.Loaded ||
            resources.answers === d.Loading ||
            resources.questionPools === d.Loading ||
            resources.questionSets === d.Loading) {
            return false;
        }
        return true;
    }
    handleSaveAnswer(event) {
        if (this.useExternal) {
            return;
        }
        const pendingUpdate = this.questionSets.pendingActiveAnswerUpdate;
        const { answer, new_value } = event.detail;
        const updatedAnswer = Sa(answer, new_value);
        if ($$(answer, new_value) ||
            (Ur(updatedAnswer) && !answer.is_completed) ||
            ((pendingUpdate === null || pendingUpdate === void 0 ? void 0 : pendingUpdate.id) === answer.id && $$(pendingUpdate, new_value))) {
            this.pushAnswer(updatedAnswer);
        }
    }
    componentWillUpdate() {
        this.handleSubscriptions();
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (h("bp-sdk-external-question-set-container", { answersResourceState: this.answersResourceState, applicationFormResourceState: this.applicationFormResourceState, config: this.config, enableUserApplicationGuard: this.enableUserApplicationGuard, hasPermissionToEdit: this.hasPermissionToEdit, isOwner: this.isOwner, locked: this.locked, pendingProcesses: this.pendingProcesses, questionPoolResourceState: this.questionPoolResourceState, questionSetResourceState: this.questionSetResourceState, questionSets: this.questionSets, queue: this.queue }));
    }
    renderQuestionSetHeader(set) {
        var _a, _b, _c, _d;
        return (h("bp-sdk-question-set-header", { applicationId: set.application_form_id, code: (_a = set.question_set) === null || _a === void 0 ? void 0 : _a.code, isActive: set.is_active, isCompleted: set.is_completed, name: (_b = set.question_set) === null || _b === void 0 ? void 0 : _b.name, setId: set.question_set_id, setTitle: (_c = set.question_set) === null || _c === void 0 ? void 0 : _c.title, tenantId: (_d = set.question_set) === null || _d === void 0 ? void 0 : _d.tenant_id }));
    }
    shouldRenderQuestionGroup(questionGroupsWithAnswersAsKey, answer) {
        return questionGroupsWithAnswersAsKey.has(answer.id);
    }
    renderQuestionSet(set) {
        // Gets multiple separate groups/nested groups
        const questionGroupsWithAnswersAsKey = h1(set, _1(set));
        if (set.is_blank) {
            return h("bp-sdk-question-set-empty", { questionSet: set.question_set });
        }
        return (h("bp-sdk-question-set", { areResourcesReady: this.areResourcesReady, canSave: this.canSave, locked: this.isLocked, questionSet: set, saveHandler: this.handleSaveQuestionSet, questionGroupsWithAnswersAsKey: questionGroupsWithAnswersAsKey, shouldRenderQuestionGroup: this.shouldRenderQuestionGroup }));
    }
    renderPendingProcessesContainer() {
        return h("bp-sdk-pending-process-container", { pendingProcesses: this.pendingProcesses });
    }
    renderInternal() {
        let activeQuestionSet = this.questionSets.list[this.questionSets.list.length - 1];
        if (this.isFirstRun && this.isLoadingApplication) {
            return h("bp-sdk-application-load", null);
        }
        if (this.questionSets.active && this.questionSets.active !== '') {
            activeQuestionSet = this.questionSets.list.find((qs) => qs.question_set_id === this.questionSets.active);
        }
        if (activeQuestionSet) {
            return (h(Fragment, null, this.renderQuestionSetHeader(activeQuestionSet), this.renderQuestionSet(activeQuestionSet), this.renderPendingProcessesContainer()));
        }
    }
    doesCurrentQuestionSetHaveAPendingProcess(processes) {
        const currentProcesses = processes ? processes : this.pendingProcesses;
        if (!(currentProcesses === null || currentProcesses === void 0 ? void 0 : currentProcesses.length)) {
            return false;
        }
        return currentProcesses.some((process) => process.state !== x.Completed && process.question_set_id === this.questionSets.active);
    }
    get el() { return getElement(this); }
    static get watchers() { return {
        "queue": ["onQueueChange"],
        "enableUserApplicationGuard": ["onEnableUserApplicationGuard"],
        "hasPermissionToEdit": ["onHasPermissionToEdit"],
        "isOwner": ["onIsOwner"],
        "locked": ["onLocked"],
        "pendingProcesses": ["onPendingProcessesChange"],
        "isFirstRun": ["onIsFirstRun"],
        "isReady": ["onIsReady"],
        "answersResourceState": ["onAnswersResourcesStateChange"],
        "applicationFormResourceState": ["onApplicationFormResourceStateChange"],
        "questionPoolResourceState": ["onQuestionPoolResourcesStateChange"],
        "questionSetResourceState": ["onQuestionSetResourcesStateChange"]
    }; }
};

export { BpSdkQuestionSetContainer as bp_sdk_question_set_container };
