import React, { useContext, useEffect, useMemo } from 'react';
import { I18nextProvider } from 'react-i18next';
import { createRenderChildNodes } from '../../createRenderChildNodes';
import { findChildElement, queryAncestors } from '../../dom-utils';
import { changeLanguage, initI18n, useExamTranslation } from '../../i18n';
import { scrollToHash } from '../../scrollToHash';
import { useCached } from '../../useCached';
import mkAttachmentLink from '../shared/AttachmentLink';
import mkAttachmentLinks from '../shared/AttachmentLinks';
import { CommonExamContext, withCommonExamContext } from '../context/CommonExamContext';
import DocumentTitle from '../DocumentTitle';
import ExamQuestionInstruction from '../exam/QuestionInstruction';
import ExamSectionTitle from '../exam/SectionTitle';
import Formula from '../shared/Formula';
import Image from '../shared/Image';
import RenderChildNodes from '../RenderChildNodes';
import { renderIf } from '../RenderIf';
import ResultsChoiceAnswer from './ChoiceAnswer';
import { ResultsContext, withResultsContext } from '../context/ResultsContext';
import DropdownAnswer from './DropdownAnswer';
import Question from './Question';
import QuestionTitle from './QuestionTitle';
import Section from './Section';
import ScoredTextAnswer from './ScoredTextAnswer';
import TextAnswer from './TextAnswer';
import { ErrorIndicatorForErrors } from '../exam/internal/ErrorIndicator';
import { validateAnswers } from '../../validateAnswers';
import { parseExamStructure } from '../../parser/parseExamStructure';
import { QuestionNumber } from '../shared/QuestionNumber';
import ExamTranslation from '../shared/ExamTranslation';
import { useIsStudentsExamineExamPage } from './isExamineExamPageHook';
import classNames from 'classnames';
import { EndExamSession } from './EndExamSession';
import { Footer } from '../shared/Footer';
import { DNDAnswerContainer } from '../shared/DNDAnswerContainer';
import { AudioContainer } from './AudioContainer';
import AudioAnswer from './AudioAnswer';
const _renderChildNodes = createRenderChildNodes({
    attachment: RenderChildNodes,
    'attachment-link': mkAttachmentLink('plain'),
    'attachment-links': mkAttachmentLinks('plain'),
    'audio-group': RenderChildNodes,
    audio: {
        component: AudioContainer,
        wrapper: renderIf(element => queryAncestors(element, 'dnd-answer-container') != null)
    },
    'choice-answer': ResultsChoiceAnswer,
    'dnd-answer-container': props => React.createElement(DNDAnswerContainer, { ...props, page: "results" }),
    'dropdown-answer': DropdownAnswer,
    formula: Formula,
    question: Question,
    hints: RenderChildNodes,
    image: {
        component: Image,
        wrapper: renderIf(element => queryAncestors(element, ['choice-answer', 'dnd-answer-container']) != null)
    },
    'question-instruction': ExamQuestionInstruction,
    'question-number': QuestionNumber,
    translation: ExamTranslation,
    'question-title': QuestionTitle,
    section: Section,
    'section-title': ExamSectionTitle,
    'text-answer': TextAnswer,
    'scored-text-answer': ScoredTextAnswer,
    'scored-text-answers': RenderChildNodes,
    'audio-answer': AudioAnswer
});
const Results = ({ doc, returnToExam, endSession, studentSessionEnded = false, isPreviewPage, renderComponentOverrides }) => {
    const { date, dateTimeFormatter, dayCode, examCode, language, resolveAttachment, root, subjectLanguage } = useContext(CommonExamContext);
    const { answersByQuestionId } = useContext(ResultsContext);
    const renderChildNodes = useMemo(() => _renderChildNodes(renderComponentOverrides), [renderComponentOverrides]);
    const examTitle = findChildElement(root, 'exam-title');
    const examStylesheet = root.getAttribute('exam-stylesheet');
    const i18n = useCached(() => initI18n(language, examCode, dayCode));
    useEffect(changeLanguage(i18n, language));
    useEffect(scrollToHash, []);
    const isStudentsExamineExamPage = useIsStudentsExamineExamPage();
    const studentCanEndSession = endSession !== undefined;
    const isExamCopy = !isStudentsExamineExamPage && !isPreviewPage;
    useEffect(() => {
        window.location.hash = '';
        if (isStudentsExamineExamPage) {
            window.scrollTo(0, 0);
        }
    }, []);
    const onEndSession = () => {
        try {
            const elements = document.querySelectorAll('main > *:not(.e-logout-container)');
            elements.forEach(el => {
                const element = el;
                element.style.height = `${element.clientHeight}px`;
            });
            setTimeout(() => {
                // eslint-disable-next-line promise/prefer-await-to-then
                void endSession().catch(e => {
                    console.error('Ending session failed', e);
                    throw e;
                });
            }, 50);
        }
        catch (e) {
            console.error('Ending session failed', e);
        }
    };
    return (React.createElement(I18nextProvider, { i18n: i18n },
        React.createElement("main", { className: classNames('e-exam e-results', {
                'examine-exam-page': isStudentsExamineExamPage,
                'session-ended': studentSessionEnded
            }), lang: subjectLanguage },
            React.createElement(React.StrictMode, null),
            examStylesheet && React.createElement("link", { rel: "stylesheet", href: resolveAttachment(examStylesheet) }),
            !isExamCopy && (React.createElement("button", { className: "e-exam-done-return js-exam-done-return e-button", onClick: returnToExam },
                "\u00AB ",
                React.createElement(BackToExamText, null))),
            React.createElement("div", { className: "e-columns e-columns--bottom-v e-mrg-b-4" },
                examTitle && (React.createElement(DocumentTitle, { id: "title", className: "e-column e-mrg-b-0" },
                    renderChildNodes(examTitle),
                    date && `, ${dateTimeFormatter.format(date)}`)),
                !isStudentsExamineExamPage && React.createElement(ScoresAndFinalGrade, null)),
            !isExamCopy && React.createElement(ExamineExamInstructions, null),
            React.createElement(ErrorIndicatorForErrors, { validationErrors: validateAnswers(parseExamStructure(doc), answersByQuestionId), inExam: false }),
            renderChildNodes(root),
            (studentCanEndSession || isPreviewPage) && (React.createElement(EndExamSession, { onEndSession: isStudentsExamineExamPage ? onEndSession : () => Promise.resolve(), sessionEnded: studentSessionEnded }))),
        React.createElement(Footer, null)));
};
const BackToExamText = () => {
    const { t } = useExamTranslation();
    return t('examineExam.returnToExam');
};
const ExamineExamInstructions = () => {
    const { t } = useExamTranslation();
    return (React.createElement("div", { className: "e-section examine-exam-page-instructions shadow-box" },
        React.createElement("h3", null, t('examineExam.checkYourAnswersTitle')),
        React.createElement("ul", null,
            React.createElement("li", null, t('examineExam.hereAreYourAnswers')),
            React.createElement("li", null, t('examineExam.checkYourAnswers')),
            React.createElement("li", null, t('examineExam.removeExcessAnswers')),
            React.createElement("li", null,
                React.createElement("span", { className: "no-answer-example" }, t('examineExam.emptyAnswersAreHighlighted')),
                t('examineExam.thereMayBeOptionalQuestions')))));
};
function ScoresAndFinalGrade() {
    const { gradingText, totalScore } = useContext(ResultsContext);
    const { t } = useExamTranslation();
    return (React.createElement("div", { className: "e-column--narrow" },
        React.createElement("table", { className: "e-table e-table--borderless e-mrg-b-0" },
            React.createElement("tbody", null,
                React.createElement("tr", null,
                    React.createElement("th", { className: "e-pad-y-0 e-normal" }, t('grading-total')),
                    React.createElement("td", { className: "e-pad-y-0 e-semibold e-text-right" }, t('points', { count: totalScore }))),
                gradingText && (React.createElement("tr", null,
                    React.createElement("th", { className: "e-pad-y-0 e-normal" }, t('grade')),
                    React.createElement("td", { className: "e-pad-y-0 e-semibold e-text-right" }, gradingText)))))));
}
export default React.memo(withResultsContext(withCommonExamContext(Results)));
//# sourceMappingURL=Results.js.map