"use strict";
// ============================================================================
// Chatbot Main - Message
// ============================================================================
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageBase = void 0;
const react_1 = __importDefault(require("react"));
const react_markdown_1 = __importDefault(require("react-markdown"));
const remark_gfm_1 = __importDefault(require("remark-gfm"));
const react_core_1 = require("@patternfly/react-core");
const MessageLoading_1 = __importDefault(require("./MessageLoading"));
const CodeBlockMessage_1 = __importDefault(require("./CodeBlockMessage/CodeBlockMessage"));
const TextMessage_1 = __importDefault(require("./TextMessage/TextMessage"));
const FileDetailsLabel_1 = __importDefault(require("../FileDetailsLabel/FileDetailsLabel"));
const ResponseActions_1 = __importDefault(require("../ResponseActions/ResponseActions"));
const SourcesCard_1 = __importDefault(require("../SourcesCard"));
const ListItemMessage_1 = __importDefault(require("./ListMessage/ListItemMessage"));
const UnorderedListMessage_1 = __importDefault(require("./ListMessage/UnorderedListMessage"));
const OrderedListMessage_1 = __importDefault(require("./ListMessage/OrderedListMessage"));
const QuickStartTile_1 = __importDefault(require("./QuickStarts/QuickStartTile"));
const QuickResponse_1 = __importDefault(require("./QuickResponse/QuickResponse"));
const UserFeedback_1 = __importDefault(require("./UserFeedback/UserFeedback"));
const UserFeedbackComplete_1 = __importDefault(require("./UserFeedback/UserFeedbackComplete"));
const TableMessage_1 = __importDefault(require("./TableMessage/TableMessage"));
const TrMessage_1 = __importDefault(require("./TableMessage/TrMessage"));
const TdMessage_1 = __importDefault(require("./TableMessage/TdMessage"));
const TbodyMessage_1 = __importDefault(require("./TableMessage/TbodyMessage"));
const TheadMessage_1 = __importDefault(require("./TableMessage/TheadMessage"));
const ThMessage_1 = __importDefault(require("./TableMessage/ThMessage"));
const ImageMessage_1 = __importDefault(require("./ImageMessage/ImageMessage"));
const rehype_unwrap_images_1 = __importDefault(require("rehype-unwrap-images"));
const rehype_external_links_1 = __importDefault(require("rehype-external-links"));
const rehype_sanitize_1 = __importDefault(require("rehype-sanitize"));
const LinkMessage_1 = __importDefault(require("./LinkMessage/LinkMessage"));
const ErrorMessage_1 = __importDefault(require("./ErrorMessage/ErrorMessage"));
const MessageInput_1 = __importDefault(require("./MessageInput"));
const MessageBase = (_a) => {
    var { role, content, extraContent, name, avatar, timestamp, isLoading, actions, sources, botWord = 'AI', loadingWord = 'Loading message', codeBlockProps, quickResponses, quickResponseContainerProps = { numLabels: 5 }, attachments, hasRoundAvatar = true, avatarProps, quickStarts, userFeedbackForm, userFeedbackComplete, isLiveRegion = true, innerRef, tableProps, openLinkInNewTab = true, additionalRehypePlugins = [], linkProps, error, isEditable, editPlaceholder = 'Edit prompt message...', updateWord = 'Update', cancelWord = 'Cancel', onEditUpdate, onEditCancel, editFormProps, isCompact } = _a, props = __rest(_a, ["role", "content", "extraContent", "name", "avatar", "timestamp", "isLoading", "actions", "sources", "botWord", "loadingWord", "codeBlockProps", "quickResponses", "quickResponseContainerProps", "attachments", "hasRoundAvatar", "avatarProps", "quickStarts", "userFeedbackForm", "userFeedbackComplete", "isLiveRegion", "innerRef", "tableProps", "openLinkInNewTab", "additionalRehypePlugins", "linkProps", "error", "isEditable", "editPlaceholder", "updateWord", "cancelWord", "onEditUpdate", "onEditCancel", "editFormProps", "isCompact"]);
    const [messageText, setMessageText] = react_1.default.useState(content);
    react_1.default.useEffect(() => {
        setMessageText(content);
    }, [content]);
    const { beforeMainContent, afterMainContent, endContent } = extraContent || {};
    let rehypePlugins = [rehype_unwrap_images_1.default];
    if (openLinkInNewTab) {
        rehypePlugins = rehypePlugins.concat([[rehype_external_links_1.default, { target: '_blank' }, rehype_sanitize_1.default]]);
    }
    if (additionalRehypePlugins) {
        rehypePlugins.push(...additionalRehypePlugins);
    }
    let avatarClassName;
    if (avatarProps && 'className' in avatarProps) {
        const { className } = avatarProps, rest = __rest(avatarProps, ["className"]);
        avatarClassName = className;
        avatarProps = Object.assign({}, rest);
    }
    // Keep timestamps consistent between Timestamp component and aria-label
    const date = new Date();
    const dateString = timestamp !== null && timestamp !== void 0 ? timestamp : `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    const renderMessage = () => {
        if (isLoading) {
            return react_1.default.createElement(MessageLoading_1.default, { loadingWord: loadingWord });
        }
        if (isEditable) {
            return (react_1.default.createElement(react_1.default.Fragment, null,
                beforeMainContent && react_1.default.createElement(react_1.default.Fragment, null, beforeMainContent),
                react_1.default.createElement(MessageInput_1.default, Object.assign({ content: content, editPlaceholder: editPlaceholder, updateWord: updateWord, cancelWord: cancelWord, onEditUpdate: (event, text) => {
                        onEditUpdate && onEditUpdate(event);
                        setMessageText(text);
                    }, onEditCancel: onEditCancel }, editFormProps))));
        }
        return (react_1.default.createElement(react_1.default.Fragment, null,
            beforeMainContent && react_1.default.createElement(react_1.default.Fragment, null, beforeMainContent),
            error ? (react_1.default.createElement(ErrorMessage_1.default, Object.assign({}, error))) : (react_1.default.createElement(react_markdown_1.default, { components: {
                    p: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.p }, props)),
                    code: (_a) => {
                        var { children } = _a, props = __rest(_a, ["children"]);
                        return (react_1.default.createElement(CodeBlockMessage_1.default, Object.assign({}, props, codeBlockProps), children));
                    },
                    h1: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.h1 }, props)),
                    h2: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.h2 }, props)),
                    h3: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.h3 }, props)),
                    h4: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.h4 }, props)),
                    h5: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.h5 }, props)),
                    h6: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.h6 }, props)),
                    blockquote: (props) => react_1.default.createElement(TextMessage_1.default, Object.assign({ component: react_core_1.ContentVariants.blockquote }, props)),
                    ul: (props) => react_1.default.createElement(UnorderedListMessage_1.default, Object.assign({}, props)),
                    ol: (props) => react_1.default.createElement(OrderedListMessage_1.default, Object.assign({}, props)),
                    li: (props) => react_1.default.createElement(ListItemMessage_1.default, Object.assign({}, props)),
                    table: (props) => react_1.default.createElement(TableMessage_1.default, Object.assign({}, props, tableProps)),
                    tbody: (props) => react_1.default.createElement(TbodyMessage_1.default, Object.assign({}, props)),
                    thead: (props) => react_1.default.createElement(TheadMessage_1.default, Object.assign({}, props)),
                    tr: (props) => react_1.default.createElement(TrMessage_1.default, Object.assign({}, props)),
                    td: (props) => {
                        // Conflicts with Td type
                        // eslint-disable-next-line @typescript-eslint/no-unused-vars
                        const { width } = props, rest = __rest(props, ["width"]);
                        return react_1.default.createElement(TdMessage_1.default, Object.assign({}, rest));
                    },
                    th: (props) => react_1.default.createElement(ThMessage_1.default, Object.assign({}, props)),
                    img: (props) => react_1.default.createElement(ImageMessage_1.default, Object.assign({}, props)),
                    a: (props) => (react_1.default.createElement(LinkMessage_1.default, Object.assign({ href: props.href, rel: props.rel, target: props.target }, linkProps), props.children))
                }, remarkPlugins: [remark_gfm_1.default], rehypePlugins: rehypePlugins }, messageText))));
    };
    return (react_1.default.createElement("section", Object.assign({ "aria-label": `Message from ${role} - ${dateString}`, className: `pf-chatbot__message pf-chatbot__message--${role}`, "aria-live": isLiveRegion ? 'polite' : undefined, "aria-atomic": isLiveRegion ? false : undefined, ref: innerRef }, props),
        react_1.default.createElement(react_core_1.Avatar, Object.assign({ className: `pf-chatbot__message-avatar ${hasRoundAvatar ? 'pf-chatbot__message-avatar--round' : ''} ${avatarClassName ? avatarClassName : ''}`, src: avatar, alt: "" }, avatarProps)),
        react_1.default.createElement("div", { className: "pf-chatbot__message-contents" },
            react_1.default.createElement("div", { className: "pf-chatbot__message-meta" },
                name && (react_1.default.createElement("span", { className: "pf-chatbot__message-name" },
                    react_1.default.createElement(react_core_1.Truncate, { content: name }))),
                role === 'bot' && (react_1.default.createElement(react_core_1.Label, { variant: "outline", isCompact: true }, botWord)),
                react_1.default.createElement(react_core_1.Timestamp, { date: date }, timestamp)),
            react_1.default.createElement("div", { className: "pf-chatbot__message-response" },
                react_1.default.createElement("div", { className: "pf-chatbot__message-and-actions" },
                    renderMessage(),
                    afterMainContent && react_1.default.createElement(react_1.default.Fragment, null, afterMainContent),
                    !isLoading && sources && react_1.default.createElement(SourcesCard_1.default, Object.assign({}, sources, { isCompact: isCompact })),
                    quickStarts && quickStarts.quickStart && (react_1.default.createElement(QuickStartTile_1.default, { quickStart: quickStarts.quickStart, onSelectQuickStart: quickStarts.onSelectQuickStart, minuteWord: quickStarts.minuteWord, minuteWordPlural: quickStarts.minuteWordPlural, prerequisiteWord: quickStarts.prerequisiteWord, prerequisiteWordPlural: quickStarts.prerequisiteWordPlural, quickStartButtonAriaLabel: quickStarts.quickStartButtonAriaLabel, isCompact: isCompact })),
                    !isLoading && actions && react_1.default.createElement(ResponseActions_1.default, { actions: actions }),
                    userFeedbackForm && react_1.default.createElement(UserFeedback_1.default, Object.assign({}, userFeedbackForm, { timestamp: dateString, isCompact: isCompact })),
                    userFeedbackComplete && (react_1.default.createElement(UserFeedbackComplete_1.default, Object.assign({}, userFeedbackComplete, { timestamp: dateString, isCompact: isCompact }))),
                    !isLoading && quickResponses && (react_1.default.createElement(QuickResponse_1.default, { quickResponses: quickResponses, quickResponseContainerProps: quickResponseContainerProps, isCompact: isCompact }))),
                attachments && (react_1.default.createElement("div", { className: "pf-chatbot__message-attachments-container" }, attachments.map((attachment) => {
                    var _a;
                    return (react_1.default.createElement("div", { key: (_a = attachment.id) !== null && _a !== void 0 ? _a : attachment.name, className: "pf-chatbot__message-attachment" },
                        react_1.default.createElement(FileDetailsLabel_1.default, { fileName: attachment.name, fileId: attachment.id, onClose: attachment.onClose, onClick: attachment.onClick, isLoading: attachment.isLoading, closeButtonAriaLabel: attachment.closeButtonAriaLabel, languageTestId: attachment.languageTestId, spinnerTestId: attachment.spinnerTestId })));
                }))),
                !isLoading && endContent && react_1.default.createElement(react_1.default.Fragment, null, endContent)))));
};
exports.MessageBase = MessageBase;
const Message = react_1.default.forwardRef((props, ref) => (react_1.default.createElement(exports.MessageBase, Object.assign({ innerRef: ref }, props))));
exports.default = Message;
