"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommentsEditor = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_redux_1 = require("react-redux");
const rebass_1 = require("rebass");
const icons_1 = require("../../components/icons");
const Panel_1 = tslib_1.__importDefault(require("../../components/Panel"));
const SimpleButton_1 = tslib_1.__importDefault(require("../../components/SimpleButton"));
const CommentsRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/CommentsRedux"));
const InternalRedux_1 = require("../../Redux/ActionsReducers/InternalRedux");
const AdaptableContext_1 = require("../AdaptableContext");
const AdaptableInput_1 = tslib_1.__importDefault(require("../Components/AdaptableInput"));
const FormatHelper_1 = tslib_1.__importDefault(require("../../Utilities/Helpers/FormatHelper"));
// Edit Mode
// [author] [edit, delete]
// [text-editor] * this is different
// [show-all-comments-button]
// View Mode
// [author] [edit, delete]
// [text]
// [show-all-comments-button]
const CommentsEditor = (props) => {
    const { api } = (0, AdaptableContext_1.useAdaptable)();
    const showCloseButton = api.optionsApi.getCommentOptions()?.showPopupCloseButton ?? true;
    const cellAddress = (0, react_redux_1.useSelector)((state) => (0, InternalRedux_1.CommentsAndNotesSelector)(state.Internal));
    const userId = React.useMemo(() => {
        return api.optionsApi.getUserName();
    }, []);
    const commentThread = (0, react_redux_1.useSelector)((state) => CommentsRedux.GetCellCommentSelector(state.Comment, cellAddress));
    const isReadOnlyModule = api.entitlementApi.getEntitlementAccessLevelForModule('Comment') === 'ReadOnly';
    const [activeEditingComment, setActiveEditingComment] = React.useState(() => {
        /**
         * When opening the popup and there is only one comment, we want to open it in edit mode.
         * This happens usualy when a new comment is added via cell menu.
         */
        // if (cellComments?.Comments?.length === 1 && cellComments?.Comments[0].Value === '') {
        //   return cellComments?.Comments[0].Uuid;
        // }
        return null;
    });
    const [newCommentText, setNewCommentText] = React.useState('');
    const commentsWrapperRef = React.useRef(null);
    const comments = commentThread?.Comments;
    const scrollToBottom = () => {
        commentsWrapperRef?.current?.scrollTo(0, commentsWrapperRef?.current?.scrollHeight);
    };
    React.useEffect(() => {
        scrollToBottom();
    }, []);
    if (!commentThread) {
        return null;
    }
    const formatDate = (date, format) => {
        return FormatHelper_1.default.DateFormatter(date, { Pattern: format });
    };
    return (React.createElement(Panel_1.default, { color: "var(--ab-color-text-on-primary)", onClick: () => props.enableEditMode(), minWidth: 250, className: "ab-CommentPopup", onKeyDown: (event) => {
            if (event.key === 'Escape') {
                api.commentApi.hideCommentsPopup();
            }
        } },
        showCloseButton && (React.createElement(rebass_1.Flex, null,
            React.createElement(rebass_1.Box, { flex: 1 }),
            React.createElement(SimpleButton_1.default, { onClick: (event) => {
                    event.stopPropagation();
                    api.commentApi.hideCommentsPopup();
                }, variant: "text", icon: "close" }))),
        React.createElement(rebass_1.Flex, { style: {
                overflow: 'auto',
                maxHeight: 300,
            }, flexDirection: "column", ref: commentsWrapperRef }, comments &&
            comments.length > 0 &&
            comments.map((comment, index) => {
                if (!comment) {
                    return null;
                }
                const isOwnComment = comment?.Author?.UserName
                    ? comment?.Author?.UserName === userId
                    : true; // no owner means it's the current user
                return (React.createElement(rebass_1.Box, { p: 2, key: comment.Uuid ?? index, className: "ab-Comment" },
                    React.createElement(rebass_1.Flex, { mb: 2, alignItems: "center" },
                        React.createElement(rebass_1.Box, null,
                            React.createElement(rebass_1.Box, { "data-name": "comment-username", fontSize: 3, fontWeight: "bold" }, comment?.Author?.UserName),
                            comment.Timestamp && (React.createElement(rebass_1.Box, { "data-name": "comment-timestamp", fontSize: 2 }, formatDate(comment.Timestamp, api.commentApi.internalApi.getCommentsDateFormat())))),
                        React.createElement(rebass_1.Box, { flex: 1 }),
                        React.createElement(SimpleButton_1.default, { variant: "text", icon: "edit", disabled: !isOwnComment || isReadOnlyModule, onClick: () => setActiveEditingComment(comment.Uuid) }),
                        React.createElement(SimpleButton_1.default, { variant: "text", icon: "delete", disabled: !isOwnComment || isReadOnlyModule, onClick: () => {
                                api.commentApi.deleteComment(comment, cellAddress);
                                requestAnimationFrame(() => {
                                    props.onRefreshContent();
                                });
                            } })),
                    React.createElement(rebass_1.Box, { onClick: () => setActiveEditingComment(comment.Uuid) }, comment.Uuid === activeEditingComment ? (React.createElement(AdaptableInput_1.default, { autoFocus: true, width: "100%", defaultValue: comment.Value, disabled: isReadOnlyModule, onBlur: () => {
                            if (comment.Uuid === activeEditingComment) {
                                setActiveEditingComment(null);
                            }
                        }, onChange: (event) => {
                            api.commentApi.editComment({
                                ...comment,
                                Value: event.target.value,
                            }, cellAddress);
                        } })) : (React.createElement(rebass_1.Text, { "data-name": "comment-text" }, comment.Value)))));
            })),
        React.createElement(AdaptableInput_1.default, { autoFocus: !comments || comments.length === 0, value: newCommentText, disabled: isReadOnlyModule, onChange: (event) => {
                setNewCommentText(event.target.value);
            }, onKeyDown: (event) => {
                if (event.key === 'Enter') {
                    api.commentApi.addComment(newCommentText, cellAddress);
                    setNewCommentText('');
                    requestAnimationFrame(() => {
                        props.onRefreshContent();
                        scrollToBottom();
                    });
                }
            }, mt: 2, mb: "2", width: "100%", placeholder: "Write new Comment" }),
        React.createElement(SimpleButton_1.default, { width: "100%", variant: "raised", onClick: () => {
                api.settingsPanelApi.openSettingsPanel('Comment');
                api.internalApi.getAnnotationsService().hidePopup();
            } },
            React.createElement(rebass_1.Box, { mr: 2 },
                React.createElement(icons_1.Icon, { name: "folder" })),
            ' ',
            "Open all Comments")));
};
exports.CommentsEditor = CommentsEditor;
