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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import React from 'react';
import { CollaborationObjectTypes } from '@reltio/mdm-sdk';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
import { CollaborationContext } from '../contexts/CollaborationContext';
import { RelatedObjectUrisContext } from '../contexts/RelatedObjectUrisContext';
import { createDefaultComment, createDefaultEntity, createDefaultMetadata } from './CommentsContainer.test-data';
import { CommentsContainer } from './CommentsContainer';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
describe('CommentsContainer tests', function () {
    var defaultCollaborationContextValue = {
        createComment: jest.fn().mockResolvedValue(undefined),
        editComment: jest.fn().mockResolvedValue(undefined),
        createReply: jest.fn().mockResolvedValue(undefined),
        editReply: jest.fn().mockResolvedValue(undefined),
        getCommentsCount: jest.fn().mockResolvedValue(undefined),
        getCommentState: jest.fn().mockReturnValue({}),
        deleteComment: jest.fn(),
        deleteReply: jest.fn(),
        reOpenThread: jest.fn(),
        resolveThread: jest.fn(),
        updateCommentState: jest.fn(),
        clearCommentState: jest.fn(),
        getComment: jest.fn(),
        clearCurrentComment: jest.fn(),
        getComments: jest.fn(),
        sending: false,
        loading: false,
        commentsMap: {},
        currentComment: null,
        comments: [],
        pageToken: null
    };
    var defaultMdmValues = {
        metadata: createDefaultMetadata(),
        entity: createDefaultEntity(),
        tenant: { id: 'alenat', name: 'alenat' },
        user: { username: 'vyacheslav.kovyazin' },
        collaborationPath: 'https://cservice-dev.reltio.com/reltio-collaboration/tst-01',
        uiPath: 'http://localhost:3000/ui/alenat/'
    };
    var defaultProps = {
        relatedObjectUris: ['relatedEntityUri'],
        uri: 'uri1',
        objectType: CollaborationObjectTypes.ENTITY,
        showAlways: false,
        allowOnlyOneComment: false,
        onChangePopupVisibility: jest.fn()
    };
    var setUp = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.props, props = _c === void 0 ? defaultProps : _c, _d = _b.mdmValues, mdmValues = _d === void 0 ? defaultMdmValues : _d, _e = _b.collaborationContextValue, collaborationContextValue = _e === void 0 ? defaultCollaborationContextValue : _e, _f = _b.providers, CustomProviders = _f === void 0 ? React.Fragment : _f, _g = _b.withoutProviders, withoutProviders = _g === void 0 ? false : _g;
        var Providers = function (_a) {
            var children = _a.children;
            return (React.createElement(CustomProviders, null,
                React.createElement(MdmModuleProvider, { values: mdmValues },
                    React.createElement(CollaborationContext.Provider, { value: collaborationContextValue }, children))));
        };
        var user = userEvent.setup();
        return __assign({ user: user }, render(React.createElement(CommentsContainer, __assign({}, props)), { wrapper: withoutProviders ? undefined : Providers }));
    };
    it('should render nothing if CollaborationContext is not set', function () {
        var container = setUp({ withoutProviders: true }).container;
        expect(container).toBeEmptyDOMElement();
    });
    it('should render nothing if objectType is not specified in CollaborationContext', function () {
        var collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { objectTypes: [CollaborationObjectTypes.RELATION] });
        var container = setUp({ collaborationContextValue: collaborationContextValue }).container;
        expect(container).toBeEmptyDOMElement();
    });
    it('should render AddCommentButton if CollaborationContext is defined', function () {
        setUp();
        expect(screen.queryByLabelText('Add comment')).toBeInTheDocument();
        expect(screen.queryByLabelText('Show comment')).not.toBeInTheDocument();
    });
    it('should render AddCommentButton with correctly className if showAlways prop is "true"', function () {
        var props = __assign(__assign({}, defaultProps), { showAlways: true });
        setUp({ props: props });
        expect(screen.getByLabelText('Add comment')).toHaveClass('addButton', 'showAlways');
    });
    it('should render AddCommentButton with correctly className if showAlways prop is "false"', function () {
        var props = __assign(__assign({}, defaultProps), { showAlways: false });
        setUp({ props: props });
        var addCommentButton = screen.getByLabelText('Add comment');
        expect(addCommentButton).toHaveClass('addButton');
        expect(addCommentButton).not.toHaveClass('showAlways');
    });
    it('should render AddCommentButton with correctly className if open popup with new comment', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, addCommentButton;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    addCommentButton = screen.getByLabelText('Add comment');
                    return [4 /*yield*/, user.click(addCommentButton)];
                case 1:
                    _a.sent();
                    expect(screen.getByLabelText('Add comment')).toHaveClass('addButton', 'showAlways');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not render AddCommentButton if allowOnlyOneComment prop is "true" and commentsMap has open comments', function () {
        var _a;
        var commentsMap = (_a = {},
            _a[defaultProps.uri] = [{ commentId: 'id1', status: 'open', replies: 1 }],
            _a);
        var collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap });
        var props = __assign(__assign({}, defaultProps), { allowOnlyOneComment: true });
        setUp({ props: props, collaborationContextValue: collaborationContextValue });
        expect(screen.queryByLabelText('Add comment')).not.toBeInTheDocument();
    });
    it('should render CommentButton for correct uri in commentsMap', function () {
        var _a;
        var commentsMap = (_a = {},
            _a[defaultProps.uri] = [
                { commentId: 'id1', status: 'open', replies: 1 },
                { commentId: 'id2', status: 'open', replies: 2 },
                { commentId: 'id3', status: 'resolved', replies: 3 }
            ],
            _a.uri2 = [{ commentId: 'id4', status: 'open', replies: 1 }],
            _a);
        var collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap });
        setUp({ collaborationContextValue: collaborationContextValue });
        expect(screen.queryByLabelText('Add comment')).toBeInTheDocument();
        var showCommentButtons = screen.getAllByLabelText('Show comment');
        expect(showCommentButtons).toHaveLength(2);
        expect(showCommentButtons[0]).toHaveTextContent('3');
        expect(showCommentButtons[1]).toHaveTextContent('2');
    });
    it('should not render CommentButtons if there is no needed uri in commentsMap', function () {
        var commentsMap = {
            uri2: [
                { commentId: 'id1', status: 'open', replies: 1 },
                { commentId: 'id2', status: 'open', replies: 2 }
            ]
        };
        var collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap });
        setUp({ collaborationContextValue: collaborationContextValue });
        expect(screen.queryByLabelText('Add comment')).toBeInTheDocument();
        expect(screen.queryByLabelText('Show comment')).not.toBeInTheDocument();
    });
    it('should render CollaborationPopup if currentComment exists and commentsButton is clicked', function () { return __awaiter(void 0, void 0, void 0, function () {
        var currentComment, commentsMap, collaborationContextValue, user;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    currentComment = createDefaultComment();
                    commentsMap = (_a = {},
                        _a[defaultProps.uri] = [{ commentId: currentComment.commentId, status: 'open', replies: 0 }],
                        _a);
                    collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap, currentComment: currentComment });
                    user = setUp({ collaborationContextValue: collaborationContextValue }).user;
                    return [4 /*yield*/, user.click(screen.getByLabelText('Show comment'))];
                case 1:
                    _b.sent();
                    expect(screen.queryByText(currentComment.content)).toBeInTheDocument();
                    expect(screen.queryByText(defaultMdmValues.entity.label)).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('handleClickAddCommentButton handler should work correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getByLabelText('Add comment'))];
                case 1:
                    _a.sent();
                    expect(screen.queryByText('Comments')).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('handleClose handler should work correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var currentComment, commentsMap, clearCurrentComment, collaborationContextValue, user;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    currentComment = createDefaultComment();
                    commentsMap = (_a = {},
                        _a[defaultProps.uri] = [{ commentId: currentComment.commentId, status: 'open', replies: 0 }],
                        _a);
                    clearCurrentComment = jest.fn();
                    collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap, currentComment: currentComment, clearCurrentComment: clearCurrentComment });
                    user = setUp({ collaborationContextValue: collaborationContextValue }).user;
                    return [4 /*yield*/, user.click(screen.getByLabelText('Show comment'))];
                case 1:
                    _b.sent();
                    expect(screen.queryByText('Comments')).toBeInTheDocument();
                    return [4 /*yield*/, user.click(document.querySelector('.backdrop'))];
                case 2:
                    _b.sent();
                    expect(screen.queryByText('Comments')).not.toBeInTheDocument();
                    expect(clearCurrentComment).toHaveBeenCalled();
                    return [2 /*return*/];
            }
        });
    }); });
    it('handleClickCommentButton should work correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var currentComment, commentsMap, getComment, collaborationContextValue, user;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    currentComment = createDefaultComment();
                    commentsMap = (_a = {},
                        _a[defaultProps.uri] = [{ commentId: currentComment.commentId, status: 'open', replies: 0 }],
                        _a);
                    getComment = jest.fn();
                    collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap, getComment: getComment });
                    user = setUp({ collaborationContextValue: collaborationContextValue }).user;
                    return [4 /*yield*/, user.click(screen.getByLabelText('Show comment'))];
                case 1:
                    _b.sent();
                    expect(getComment).toHaveBeenCalledWith(currentComment.commentId);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChangePopupVisibility handler when anchorEl changed', function () { return __awaiter(void 0, void 0, void 0, function () {
        var onChangePopupVisibility, props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    onChangePopupVisibility = jest.fn();
                    props = __assign(__assign({}, defaultProps), { onChangePopupVisibility: onChangePopupVisibility });
                    user = setUp({ props: props }).user;
                    expect(onChangePopupVisibility).not.toHaveBeenCalled();
                    return [4 /*yield*/, user.click(screen.getByLabelText('Add comment'))];
                case 1:
                    _a.sent();
                    expect(onChangePopupVisibility).toHaveBeenCalledWith(true);
                    return [4 /*yield*/, user.click(document.querySelector('.backdrop'))];
                case 2:
                    _a.sent();
                    expect(onChangePopupVisibility).toHaveBeenCalledWith(false);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not close popup if click menu item in kebab', function () { return __awaiter(void 0, void 0, void 0, function () {
        var currentComment, commentsMap, collaborationContextValue, user;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    currentComment = createDefaultComment();
                    commentsMap = (_a = {},
                        _a[defaultProps.uri] = [{ commentId: currentComment.commentId, status: 'open', replies: 0 }],
                        _a);
                    collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { commentsMap: commentsMap, currentComment: currentComment });
                    user = setUp({ collaborationContextValue: collaborationContextValue }).user;
                    return [4 /*yield*/, user.click(screen.getByLabelText('Show comment'))];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Open menu' }))];
                case 2:
                    _b.sent();
                    expect(screen.queryByText('Comments')).toBeInTheDocument();
                    return [4 /*yield*/, user.click(document.querySelector('.backdrop'))];
                case 3:
                    _b.sent();
                    expect(screen.queryByText('Comments')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should use RelatedObjectUrisContext for collect relatedObjectUris', function () { return __awaiter(void 0, void 0, void 0, function () {
        var additionalRelatedObjectUris, createComment, getCommentState, collaborationContextValue, Providers, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    additionalRelatedObjectUris = ['additionalUri1', 'additionalUri2'];
                    createComment = jest.fn().mockReturnValue(new Promise(function (res) { return res(); }));
                    getCommentState = jest.fn().mockImplementation(function () { return ({
                        value: 'Hello @[vyacheslav](vyacheslav)',
                        plainTextValue: 'Hello +vyacheslav',
                        mentions: ['vyacheslav']
                    }); });
                    collaborationContextValue = __assign(__assign({}, defaultCollaborationContextValue), { createComment: createComment, currentComment: null, getCommentState: getCommentState });
                    Providers = function (_a) {
                        var children = _a.children;
                        return (React.createElement(RelatedObjectUrisContext.Provider, { value: additionalRelatedObjectUris }, children));
                    };
                    user = setUp({ collaborationContextValue: collaborationContextValue, providers: Providers }).user;
                    return [4 /*yield*/, user.click(screen.getByLabelText('Add comment'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByRole('button', { name: 'Comment' }))];
                case 2:
                    _a.sent();
                    expect(createComment).toHaveBeenCalledWith({
                        content: 'Hello +vyacheslav',
                        namedUsers: ['vyacheslav'],
                        objectType: 'entity',
                        relatedObjectUris: __spreadArray(['relatedEntityUri'], additionalRelatedObjectUris, true),
                        uri: 'uri1'
                    });
                    return [2 /*return*/];
            }
        });
    }); });
});
