'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 BpSdkQuestionSetContainer = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.bpAnalyticsTrack = index.createEvent(this, "bpAnalyticsTrack", 7);
        this.handleSubscriptions = () => {
            this.storeUnsubscribe && this.storeUnsubscribe();
            reduxStore_service.store.mapDispatchToProps(this, {
                saveQuestionSet: index_esm_min.an,
                updateErrors: index_esm_min.S5,
                pushAnswer: index_esm_min.wa,
                removeActiveAnswerId: index_esm_min._8,
                updateActiveAnswerId: index_esm_min.y8,
            });
            this.storeUnsubscribe = reduxStore_service.store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => {
            return {
                questionSets: state.application.questionSets,
                config: index_esm_min.up(state),
                enableUserApplicationGuard: !!state.config.options.enableUserApplicationGuard,
                locked: state.application.form.locked,
                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,
                }),
                pendingProcesses: state.application.pendingProcesses,
                queue: state.queues.answers.queue,
                answersResourceState: index_esm_min.cR(state),
                applicationFormResourceState: index_esm_min.lR(state),
                questionPoolResourceState: index_esm_min.dR(state),
                questionSetResourceState: index_esm_min.fR(state),
            };
        };
        this.handleSaveQuestionSet = (questionSet) => {
            const invalidAnswers = questionSet.answers.filter((answer) => !index_esm_min$2.hi(answer));
            if (!invalidAnswers.length) {
                this.removeActiveAnswerId();
                this.saveQuestionSet({
                    config: this.config,
                    appFormQuestionSet: questionSet,
                    navigationDirection: 'forward',
                });
                this.bpAnalyticsTrack.emit({
                    eventName: index_esm_min$1.he.QuestionSetSaved,
                    eventPayload: {
                        applicationFormQuestionSetId: questionSet.id,
                        questionSetId: questionSet.question_set_id,
                        questionSetCode: questionSet.question_set.code,
                    },
                });
            }
            else {
                invalidAnswers.forEach((answer) => {
                    this.updateErrors({ answer, errors: index_esm_min$2.Jr(answer) });
                });
                index_esm_min$2.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 === index_esm_min$1.d.Loaded) {
            this.isFirstRun = false;
        }
        if (state === index_esm_min$1.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 !== 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;
    }
    handleSaveAnswer(event) {
        if (this.useExternal) {
            return;
        }
        const pendingUpdate = this.questionSets.pendingActiveAnswerUpdate;
        const { answer, new_value } = event.detail;
        const updatedAnswer = index_esm_min$2.Sa(answer, new_value);
        if (index_esm_min$2.$$(answer, new_value) ||
            (index_esm_min$2.Ur(updatedAnswer) && !answer.is_completed) ||
            ((pendingUpdate === null || pendingUpdate === void 0 ? void 0 : pendingUpdate.id) === answer.id && index_esm_min$2.$$(pendingUpdate, new_value))) {
            this.pushAnswer(updatedAnswer);
        }
    }
    componentWillUpdate() {
        this.handleSubscriptions();
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (index.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 (index.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 = index_esm_min$2.h1(set, index_esm_min$2._1(set));
        if (set.is_blank) {
            return index.h("bp-sdk-question-set-empty", { questionSet: set.question_set });
        }
        return (index.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 index.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 index.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 (index.h(index.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 !== index_esm_min$1.x.Completed && process.question_set_id === this.questionSets.active);
    }
    get el() { return index.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"]
    }; }
};

exports.bp_sdk_question_set_container = BpSdkQuestionSetContainer;
