"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const styles_1 = require("@mui/material/styles");
const material_1 = require("@mui/material");
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const MessageMediaUploader_1 = tslib_1.__importDefault(require("./MessageMediaUploader"));
const react_intl_1 = require("react-intl");
const system_1 = require("@mui/system");
const EmojiPicker_1 = tslib_1.__importDefault(require("../../shared/EmojiPicker"));
const utils_1 = require("@selfcommunity/utils");
const constants_1 = require("./constants");
const messages = (0, react_intl_1.defineMessages)({
    placeholder: {
        id: 'ui.privateMessage.editor.placeholder',
        defaultMessage: 'ui.privateMessage.editor.placeholder'
    }
});
const classes = {
    root: `${constants_1.PREFIX}-root`,
    ios: `${constants_1.PREFIX}-ios`,
    messageInput: `${constants_1.PREFIX}-message-input`,
    mediaUploader: `${constants_1.PREFIX}-media-uploader`,
    emojiSection: `${constants_1.PREFIX}-emoji-section`
};
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
/**
 * > API documentation for the Community-JS Private Message Editor component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {PrivateMessageEditor} from '@selfcommunity/react-ui';
 ```

 #### Component Name

 The name `SCPrivateMessageEditor` can be used when providing style overrides in the theme.


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCPrivateMessageEditor-root|Styles applied to the root element.|
 |messageInput|.SCPrivateMessageEditor-card|Styles applied to the message input element.|
 |mediaUploader|.SCPrivateMessageEditor-media-uploader|Styles applied to the message media uploader section.|
 |emojiSection|.SCPrivateMessageEditor-emoji-section|Styles applied to the emoji section.|

 * @param inProps
 */
function PrivateMessageEditor(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { autoHide = null, className = null, send = null, onThreadChangeId, error = false, onErrorRemove = null, autoHideDeletion } = props, rest = tslib_1.__rest(props, ["autoHide", "className", "send", "onThreadChangeId", "error", "onErrorRemove", "autoHideDeletion"]);
    // STATE
    const [message, setMessage] = (0, react_1.useState)('');
    const [messageFiles, setMessageFiles] = (0, react_1.useState)([]);
    const [openMediaSection, setOpenMediaSection] = (0, react_1.useState)(false);
    const [openEmojiSection, setOpenEmojiSection] = (0, react_1.useState)(false);
    const [threadId, setThreadId] = (0, react_1.useState)(null);
    const [uploading, setUploading] = (0, react_1.useState)(false);
    // INTL
    const intl = (0, react_intl_1.useIntl)();
    // REF
    const ref = (0, react_1.useRef)(null);
    // HANDLERS
    const handleMediaSectionClose = () => {
        setOpenMediaSection(false);
        setMessageFiles([]);
    };
    const handleMessageFiles = (f) => {
        setMessageFiles(f);
    };
    const handleMessageSend = () => {
        if (messageFiles.length) {
            messageFiles.map((file) => {
                send(message, file.file_uuid);
            });
        }
        else {
            send(message, '');
        }
        setMessage('');
        setMessageFiles([]);
        setOpenMediaSection(false);
        setOpenEmojiSection(false);
    };
    const handleMessageInput = (event) => {
        setMessage(event.target.value);
    };
    const handleEmojiClick = (emojiData, event) => {
        const cursorPosition = ref.current.selectionEnd;
        const start = ref.current.value.substring(0, ref.current.selectionStart);
        const end = ref.current.value.substring(ref.current.selectionStart);
        setMessage(start + emojiData.emoji + end);
        setTimeout(() => {
            ref.current.selectionStart = ref.current.selectionEnd = cursorPosition + emojiData.emoji.length;
        }, 50);
    };
    // EFFECTS
    (0, react_1.useEffect)(() => {
        setThreadId(onThreadChangeId);
        if (threadId !== onThreadChangeId) {
            setMessage('');
            setMessageFiles([]);
            setOpenMediaSection(false);
        }
    }, [onThreadChangeId]);
    // MEMO
    const isIOS = (0, react_1.useMemo)(() => (0, utils_1.iOS)(), []);
    /**
     * Rendering
     */
    if (autoHide || autoHideDeletion) {
        return ((0, jsx_runtime_1.jsx)(material_1.Alert, Object.assign({ severity: autoHideDeletion ? 'warning' : 'info' }, { children: autoHideDeletion ? ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.privateMessage.editor.disabled.deleted.msg", defaultMessage: "ui.privateMessage.editor.disabled.deleted.msg" })) : ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.privateMessage.editor.disabled.msg", defaultMessage: "ui.privateMessage.editor.disabled.msg" })) })));
    }
    else if (error) {
        return ((0, jsx_runtime_1.jsx)(material_1.Alert, Object.assign({ severity: "error", action: (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ color: "inherit", size: "small", onClick: onErrorRemove }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "close" }) })) }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.privateMessage.editor.error.send.msg", defaultMessage: "ui.privateMessage.editor.error.send.msg" }) })));
    }
    function renderContent() {
        return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: openMediaSection ? ((0, jsx_runtime_1.jsx)(MessageMediaUploader_1.default, { className: classes.mediaUploader, open: openMediaSection, onClose: handleMediaSectionClose, forwardMessageFile: handleMessageFiles, isUploading: setUploading, action: (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ disabled: (!message && !messageFiles.length) || uploading, onClick: handleMessageSend }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "send" }) })) })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [openEmojiSection && (0, jsx_runtime_1.jsx)(EmojiPicker_1.default, { className: classes.emojiSection, onEmojiClick: handleEmojiClick, width: "100%", searchDisabled: true }), (0, jsx_runtime_1.jsx)(material_1.TextField, { size: "small", inputRef: ref, disabled: Boolean(messageFiles.length) || openMediaSection, className: classes.messageInput, multiline: true, placeholder: `${intl.formatMessage(messages.placeholder)}`, value: message, onChange: handleMessageInput, maxRows: 2, onSelect: () => setOpenEmojiSection(false), InputProps: {
                            startAdornment: ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ disabled: openMediaSection, onClick: () => setOpenEmojiSection(!openEmojiSection) }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "sentiment_satisfied_alt" }) })), (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ disabled: message !== '' || openEmojiSection, onClick: () => setOpenMediaSection(true) }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "attach_file" }) }))] })),
                            endAdornment: ((0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ disabled: (!message && !messageFiles.length) || uploading, onClick: handleMessageSend }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "send" }) })))
                        } })] })) }));
    }
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({}, rest, { className: (0, classnames_1.default)(classes.root, className, { [classes.ios]: isIOS }) }, { children: renderContent() })));
}
exports.default = PrivateMessageEditor;
