"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var MdmModuleContext_1 = require("../../../contexts/MdmModuleContext");
var CollaborationContext_1 = require("../../../contexts/CollaborationContext");
var SendMessageArea_1 = require("./SendMessageArea");
var user_event_1 = __importDefault(require("@testing-library/user-event"));
var react_2 = require("@testing-library/react");
var ramda_1 = require("ramda");
describe('SendMessageArea tests', function () {
    var mdmValues = {
        user: {
            username: 'egor.ivanov'
        }
    };
    var createCommentObject = function (commentObject) {
        if (commentObject === void 0) { commentObject = {}; }
        return __assign({ selfLink: 'selfLink', commentId: 'commentId', createdBy: 'created by user', createdTime: 1, modifiedTime: 2, deleted: false, visibility: 'visible', objectId: 'id1', objectType: mdm_sdk_1.CollaborationObjectTypes.ENTITY, permanentLink: 'permanentLink', content: 'commentContent', namedUsers: ['user1'], replies: [], relatedObjectUris: ['uri1'], status: 'open' }, commentObject);
    };
    var createCollaborationContext = function (props) {
        if (props === void 0) { props = {}; }
        return __assign({ comments: [], commentsMap: null, totalCommentsCount: null, currentComment: null, getComment: ramda_1.identity, getComments: function () { return new Promise(ramda_1.identity); }, getCommentsCount: ramda_1.identity, resolveThread: ramda_1.identity, reOpenThread: ramda_1.identity, clearCurrentComment: ramda_1.identity, deleteComment: ramda_1.identity, sending: false, loading: false, pageToken: null, deleteReply: ramda_1.identity, createReply: function () { return new Promise(function (res) { return res(); }); }, createComment: function () { return new Promise(function (res) { return res(); }); }, editComment: function () { return new Promise(function (res) { return res(); }); }, editReply: function () { return new Promise(function (res) { return res(); }); }, getCommentState: function () { return ({}); }, clearCommentState: function () { }, updateCommentState: function () { } }, props);
    };
    var createProps = function (comment, extraProps) {
        if (extraProps === void 0) { extraProps = {}; }
        return __assign(__assign({ comment: comment, inputRef: react_1.default.createRef() }, extraProps), { objectType: mdm_sdk_1.CollaborationObjectTypes.ENTITY, uri: 'uri', relatedObjectUris: ['entities/13JKIKAz'], className: 'root' });
    };
    var setUp = function (_a) {
        var props = _a.props, _b = _a.collaborationContextValue, collaborationContextValue = _b === void 0 ? createCollaborationContext() : _b;
        var Providers = function (_a) {
            var children = _a.children;
            return (react_1.default.createElement(CollaborationContext_1.CollaborationContext.Provider, { value: collaborationContextValue },
                react_1.default.createElement(MdmModuleContext_1.MdmModuleProvider, { values: mdmValues }, children)));
        };
        var user = user_event_1.default.setup();
        return __assign({ user: user }, (0, react_2.render)(react_1.default.createElement(SendMessageArea_1.SendMessageArea, __assign({}, props)), { wrapper: Providers }));
    };
    it('should render avatar correctly', function () {
        setUp({
            props: createProps(createCommentObject({ status: 'open' }))
        });
        expect(react_2.screen.queryByText('EI')).toBeInTheDocument();
    });
    it('should render input correctly if status is "open"', function () {
        setUp({
            props: createProps(createCommentObject({ status: 'open' }))
        });
        expect(react_2.screen.queryByPlaceholderText('Reply...')).toBeInTheDocument();
    });
    it('should render input correctly if status is "resolved"', function () {
        setUp({
            props: createProps(createCommentObject({ status: 'resolved' }))
        });
        expect(react_2.screen.queryByPlaceholderText('Adding a comment will re-open this')).toBeInTheDocument();
    });
    it('should render input correctly if status is undefined', function () {
        setUp({
            props: createProps()
        });
        expect(react_2.screen.getByRole('textbox')).toHaveAttribute('placeholder', '');
    });
    it('should render Reply button correctly if status is "open"', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'open' }))
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.getByRole('button', { name: 'Reply' })).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render Reply button correctly if status is "resolved"', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'resolved' }))
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.getByRole('button', { name: 'Reply' })).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render Comment button correctly if comment is undefined', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({
                        props: createProps()
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.getByRole('button', { name: 'Comment' })).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render buttons if value is not empty string', function () {
        var getCommentState = jest.fn().mockImplementation(function () { return ({
            value: 'value',
            plainTextValue: 'value',
            mentions: []
        }); });
        setUp({
            props: createProps(),
            collaborationContextValue: createCollaborationContext({ getCommentState: getCommentState })
        });
        expect(react_2.screen.queryAllByRole('button')).toHaveLength(2);
    });
    it('should render buttons if input is focused', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'open' }))
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.queryAllByRole('button')).toHaveLength(2);
                    return [4 /*yield*/, user_event_1.default.tab()];
                case 2:
                    _a.sent();
                    expect(react_2.screen.queryAllByRole('button')).toHaveLength(0);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should disable Reply or Comment button if value is empty', function () { return __awaiter(void 0, void 0, void 0, function () {
        var getCommentState, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: '',
                        plainTextValue: '',
                        mentions: []
                    }); });
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'open' })),
                        collaborationContextValue: createCollaborationContext({ getCommentState: getCommentState })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.queryByRole('button', { name: 'Reply' })).toBeDisabled();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should disable Cancel button if sending is "true"', function () { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            setUp({
                props: createProps(createCommentObject({ status: 'open' })),
                collaborationContextValue: createCollaborationContext({ sending: true })
            });
            react_2.fireEvent.focus(react_2.screen.getByRole('textbox'));
            expect(react_2.screen.queryByRole('button', { name: 'Cancel' })).toBeDisabled();
            return [2 /*return*/];
        });
    }); });
    it('should disable Reply or Comment button if sending is "true"', function () {
        setUp({
            props: createProps(createCommentObject({ status: 'open' })),
            collaborationContextValue: createCollaborationContext({ sending: true })
        });
        react_2.fireEvent.focus(react_2.screen.getByRole('textbox'));
        expect(react_2.screen.queryByRole('button', { name: 'Reply' })).toBeDisabled();
    });
    it('should pass correct default value to TextFieldWithMentions if isEditingComment equals true', function () {
        var comment = {
            content: 'Hello +denis',
            namedUsers: ['denis']
        };
        setUp({
            props: createProps(createCommentObject(comment), { isEditingComment: true })
        });
        expect(react_2.screen.getByPlaceholderText('Reply...')).toHaveTextContent('Hello +denis');
    });
    it('should pass correct default value to TextFieldWithMentions if isEditingReply equals true', function () {
        var reply = {
            content: 'Hello +ainsteisha',
            namedUsers: ['ainsteisha'],
            replyId: 'replyId'
        };
        setUp({
            props: createProps(createCommentObject(), { isEditingReply: true, reply: reply })
        });
        expect(react_2.screen.getByPlaceholderText('Reply...')).toHaveTextContent('Hello +ainsteisha');
    });
    it('should pass correct default value to TextFieldWithMentions if isEditingReply and isEditingComment equals false', function () {
        setUp({
            props: createProps(createCommentObject())
        });
        expect(react_2.screen.getByPlaceholderText('Reply...')).toHaveTextContent('');
    });
    it('handleChange handler should work correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var value, plainTextValue, mentions, getCommentState, updateCommentState, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    value = 'Hello @[vyacheslav](vyacheslav)';
                    plainTextValue = 'Hello +vyacheslav';
                    mentions = ['vyacheslav'];
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: value,
                        plainTextValue: plainTextValue,
                        mentions: mentions
                    }); });
                    updateCommentState = jest.fn();
                    user = setUp({
                        props: createProps(),
                        collaborationContextValue: createCollaborationContext({ getCommentState: getCommentState, updateCommentState: updateCommentState })
                    }).user;
                    return [4 /*yield*/, user.type(react_2.screen.getByRole('textbox'), ' ')];
                case 1:
                    _a.sent();
                    expect(updateCommentState).toHaveBeenCalledWith('uri', 'comment/new', {
                        value: "".concat(value, " "),
                        plainTextValue: "".concat(plainTextValue, " "),
                        mentions: mentions
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('handleSubmit handler should work correctly if comment exists and last status is "open"', function () { return __awaiter(void 0, void 0, void 0, function () {
        var getCommentState, clearCommentState, createReply, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: 'Hello @[vyacheslav](vyacheslav)',
                        plainTextValue: 'Hello +vyacheslav',
                        mentions: ['vyacheslav']
                    }); });
                    clearCommentState = jest.fn();
                    createReply = jest.fn().mockReturnValue(new Promise(function (res) { return res(); }));
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'open' })),
                        collaborationContextValue: createCollaborationContext({ getCommentState: getCommentState, createReply: createReply, clearCommentState: clearCommentState })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Reply' }))];
                case 1:
                    _a.sent();
                    expect(createReply).toHaveBeenCalledWith({
                        content: 'Hello +vyacheslav',
                        namedUsers: ['vyacheslav'],
                        commentId: 'commentId',
                        action: 'none',
                        uri: 'uri'
                    });
                    expect(clearCommentState).toHaveBeenCalledWith('uri', 'comment/commentId/reply/new');
                    return [2 /*return*/];
            }
        });
    }); });
    it('handleSubmit handler should work correctly if comment exists and last status is "resolved"', function () { return __awaiter(void 0, void 0, void 0, function () {
        var getCommentState, createReply, clearCommentState, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: 'Hello @[vyacheslav](vyacheslav)',
                        plainTextValue: 'Hello +vyacheslav',
                        mentions: ['vyacheslav']
                    }); });
                    createReply = jest.fn().mockReturnValue(new Promise(function (res) { return res(); }));
                    clearCommentState = jest.fn();
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'resolved' })),
                        collaborationContextValue: createCollaborationContext({ getCommentState: getCommentState, createReply: createReply, clearCommentState: clearCommentState })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Reply' }))];
                case 1:
                    _a.sent();
                    expect(createReply).toHaveBeenCalledWith({
                        content: 'Hello +vyacheslav',
                        namedUsers: ['vyacheslav'],
                        commentId: 'commentId',
                        action: 'reopen',
                        uri: 'uri'
                    });
                    expect(clearCommentState).toHaveBeenCalledWith('uri', 'comment/commentId/reply/new');
                    return [2 /*return*/];
            }
        });
    }); });
    it('handleSubmit handler should work correctly if comment does not exist', function () { return __awaiter(void 0, void 0, void 0, function () {
        var getCommentState, clearCommentState, createComment, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: 'Hello @[vyacheslav](vyacheslav)',
                        plainTextValue: 'Hello +vyacheslav',
                        mentions: ['vyacheslav']
                    }); });
                    clearCommentState = jest.fn();
                    createComment = jest.fn().mockReturnValue(new Promise(function (res) { return res(); }));
                    user = setUp({
                        props: createProps(),
                        collaborationContextValue: createCollaborationContext({ getCommentState: getCommentState, createComment: createComment, clearCommentState: clearCommentState })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Comment' }))];
                case 1:
                    _a.sent();
                    expect(createComment).toHaveBeenCalledWith({
                        content: 'Hello +vyacheslav',
                        namedUsers: ['vyacheslav'],
                        objectType: 'entity',
                        uri: 'uri',
                        relatedObjectUris: ['entities/13JKIKAz']
                    });
                    expect(clearCommentState).toHaveBeenCalledWith('uri', 'comment/new');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render Edit button if isEditingComment prop is true', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({
                        props: createProps(createCommentObject({ status: 'resolved' }), { isEditingComment: true })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('textbox'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.queryByRole('button', { name: 'Edit' })).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('submitting should work correctly if comment is editing', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onCancel, editComment, clearCommentState, comment, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    onCancel = jest.fn();
                    editComment = jest.fn().mockReturnValue(new Promise(function (res) { return res(); }));
                    clearCommentState = jest.fn();
                    comment = {
                        content: 'Hello +denis',
                        namedUsers: ['denis']
                    };
                    user = setUp({
                        props: createProps(createCommentObject(comment), { isEditingComment: true, onCancel: onCancel }),
                        collaborationContextValue: createCollaborationContext({ editComment: editComment, clearCommentState: clearCommentState })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Edit' }))];
                case 1:
                    _a.sent();
                    expect(editComment).toHaveBeenCalledWith({
                        content: 'Hello +denis',
                        namedUsers: ['denis'],
                        commentId: 'commentId',
                        uri: 'uri',
                        relatedObjectUris: ['entities/13JKIKAz'],
                        replies: [],
                        objectType: 'entity'
                    });
                    expect(clearCommentState).toHaveBeenCalledWith('uri', 'comment/commentId');
                    expect(onCancel).toHaveBeenCalledTimes(1);
                    return [2 /*return*/];
            }
        });
    }); });
    it('submitting should work correctly if reply is editing', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onCancel, editReply, clearCommentState, reply, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    onCancel = jest.fn();
                    editReply = jest.fn().mockReturnValue(new Promise(function (res) { return res(); }));
                    clearCommentState = jest.fn();
                    reply = {
                        content: 'Hello +ainsteisha',
                        namedUsers: ['ainsteisha'],
                        replyId: 'replyId'
                    };
                    user = setUp({
                        props: createProps(createCommentObject(), {
                            isEditingReply: true,
                            onCancel: onCancel,
                            reply: reply
                        }),
                        collaborationContextValue: createCollaborationContext({ editReply: editReply, clearCommentState: clearCommentState })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Edit' }))];
                case 1:
                    _a.sent();
                    expect(editReply).toHaveBeenCalledWith({
                        content: reply.content,
                        namedUsers: reply.namedUsers,
                        commentId: 'commentId',
                        replyId: reply.replyId
                    });
                    expect(clearCommentState).toHaveBeenCalledWith('uri', 'comment/commentId/reply/replyId');
                    expect(onCancel).toHaveBeenCalledTimes(1);
                    return [2 /*return*/];
            }
        });
    }); });
    it('if received error after send request, do not need to clear text input', function () { return __awaiter(void 0, void 0, void 0, function () {
        var editCommentWithReject, clearCommentState, getCommentState, onCancel, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    editCommentWithReject = jest.fn().mockRejectedValue('error');
                    clearCommentState = jest.fn();
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: 'Hello @[+vyacheslav](vyacheslav)',
                        plainTextValue: 'Hello +vyacheslav',
                        mentions: ['vyacheslav']
                    }); });
                    onCancel = jest.fn();
                    user = setUp({
                        props: createProps(createCommentObject(), { isEditingComment: true, onCancel: onCancel }),
                        collaborationContextValue: createCollaborationContext({
                            sending: false,
                            editComment: editCommentWithReject,
                            getCommentState: getCommentState,
                            clearCommentState: clearCommentState
                        })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Edit' }))];
                case 1:
                    _a.sent();
                    expect(clearCommentState).not.toHaveBeenCalled();
                    expect(onCancel).toHaveBeenCalledTimes(0);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onCancel if click cancel button', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onCancel, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    onCancel = jest.fn();
                    user = setUp({
                        props: createProps(createCommentObject(), { isEditingComment: true, onCancel: onCancel })
                    }).user;
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('button', { name: 'Cancel' }))];
                case 1:
                    _a.sent();
                    expect(onCancel).toHaveBeenCalledTimes(1);
                    return [2 /*return*/];
            }
        });
    }); });
});
