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 };
    }
};
import React from 'react';
import { mockResizeObserver } from 'jsdom-testing-mocks';
import { act, render, screen, waitForElementToBeRemoved, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { insertDefaultImageByAttrUri, Mode } from '@reltio/mdm-sdk';
import { imageAttributeValues, attributeType } from './imageAttributeValues.test-data';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
import { BlockImageGalleryDialogContext } from '../contexts/BlockImageGalleryDialogContext';
import { downloadImagesByURLs } from './helpers';
import { ImageAttributesLine } from './ImageAttributesLine';
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { insertDefaultImageByAttrUri: jest.fn() })); });
jest.mock('./helpers', function () { return (__assign(__assign({}, jest.requireActual('./helpers')), { downloadImagesByURLs: jest.fn() })); });
describe('ImageAttributesLine tests', function () {
    var resizeObserver = mockResizeObserver();
    var renderImage = function (_a) {
        var onOpenImageGalleryDialog = _a.onOpenImageGalleryDialog, onDownload = _a.onDownload, onShareLink = _a.onShareLink, onSetAsDefault = _a.onSetAsDefault;
        var renderImage = function (attributeValue) { return (React.createElement("div", { key: attributeValue.uri, "data-reltio-id": "image" },
            React.createElement("div", { "data-reltio-id": "image-content", onClick: function () { return onOpenImageGalleryDialog(attributeValue.uri); } }),
            onDownload && React.createElement("div", { "data-reltio-id": "download", onClick: function () { return onDownload([attributeValue.uri]); } }),
            onShareLink && React.createElement("div", { "data-reltio-id": "share", onClick: function () { return onShareLink(attributeValue.uri); } }),
            onSetAsDefault && (React.createElement("div", { "data-reltio-id": "set-as-default", onClick: function () { return onSetAsDefault(attributeValue); } })))); };
        return renderImage;
    };
    var defaultProps = {
        attributeValues: [],
        attributeType: attributeType,
        renderImage: renderImage
    };
    var defaultMdmValues = {
        entity: { uri: 'entities/123', type: 'configuration/entityTypes/HCP' },
        modifiedEntities: {
            'entities/123': { uri: 'entities/123', type: 'configuration/entityTypes/HCP', attributes: {} }
        },
        mode: Mode.Viewing
    };
    var defaultMdmActions = {
        setDefaultProfilePicForModifiedEntity: jest.fn(),
        setDefaultProfilePicForEntity: jest.fn()
    };
    var setUp = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.props, props = _c === void 0 ? {} : _c, _d = _b.mdmValues, mdmValues = _d === void 0 ? {} : _d, _e = _b.mdmActions, mdmActions = _e === void 0 ? {} : _e, _f = _b.blockDialogContextValue, blockDialogContextValue = _f === void 0 ? false : _f;
        var user = userEvent.setup();
        var Providers = function (_a) {
            var children = _a.children;
            return (React.createElement(MdmModuleProvider, { values: __assign(__assign({}, defaultMdmValues), mdmValues), actions: __assign(__assign({}, defaultMdmActions), mdmActions) },
                React.createElement(BlockImageGalleryDialogContext.Provider, { value: blockDialogContextValue }, children)));
        };
        return __assign({ user: user }, render(React.createElement(ImageAttributesLine, __assign({}, defaultProps, props)), { wrapper: Providers }));
    };
    beforeEach(function () {
        jest.clearAllMocks();
        downloadImagesByURLs.mockReturnValue(undefined);
        insertDefaultImageByAttrUri.mockResolvedValue({ status: 'success' });
    });
    it('should resize component', function () { return __awaiter(void 0, void 0, void 0, function () {
        var container;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    container = setUp({ props: { attributeValues: imageAttributeValues } }).container;
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    expect(screen.getAllByTestId('image')).toHaveLength(3);
                    expect(screen.queryByTestId('more-image-button')).not.toBeInTheDocument();
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
                    act(function () {
                        resizeObserver.resize(container);
                    });
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+1'); })];
                case 1:
                    _a.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(2);
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 239 } });
                    act(function () {
                        resizeObserver.resize(container);
                    });
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+2'); })];
                case 2:
                    _a.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(2);
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 240 } });
                    act(function () {
                        resizeObserver.resize(container);
                    });
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+1'); })];
                case 3:
                    _a.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(2);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should recalculate max items to screen width after attributeValues.length changing', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, rerender, newAttributeValues;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp({ props: { attributeValues: imageAttributeValues } }), container = _a.container, rerender = _a.rerender;
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    expect(screen.getAllByTestId('image')).toHaveLength(3);
                    expect(screen.queryByTestId('more-image-button')).not.toBeInTheDocument();
                    rerender(React.createElement(ImageAttributesLine, __assign({}, defaultProps, { attributeValues: [imageAttributeValues[0]] })));
                    expect(screen.getAllByTestId('image')).toHaveLength(1);
                    expect(screen.queryByTestId('more-image-button')).not.toBeInTheDocument();
                    newAttributeValues = Array.from({ length: 6 }, function (_, i) { return (__assign(__assign({}, imageAttributeValues[0]), { uri: imageAttributeValues[0].uri + i })); });
                    rerender(React.createElement(ImageAttributesLine, __assign({}, defaultProps, { attributeValues: newAttributeValues })));
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+1'); })];
                case 1:
                    _b.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(5);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should open ImageAttributesGallery when click to image or button if BlockImageGalleryDialogContext context has falsy value', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, user;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp({
                        props: { attributeValues: imageAttributeValues },
                        blockDialogContextValue: false
                    }), container = _a.container, user = _a.user;
                    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    return [4 /*yield*/, user.click(screen.getAllByTestId('image-content')[0])];
                case 1:
                    _b.sent();
                    expect(screen.getByRole('dialog')).toBeInTheDocument();
                    expect(screen.getByTestId('thumbnails-container').childNodes).toHaveLength(3);
                    expect(screen.getByText('Gallery')).toBeInTheDocument();
                    expect(screen.getByText('Meta info')).toBeInTheDocument();
                    expect(screen.getAllByTestId('image-meta-info-item')[0].querySelector('.link')).toHaveAttribute('href', '/test.jpg');
                    return [4 /*yield*/, user.click(screen.getByLabelText('Close'))];
                case 2:
                    _b.sent();
                    return [4 /*yield*/, waitForElementToBeRemoved(screen.queryByRole('dialog'))];
                case 3:
                    _b.sent();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not open ImageAttributesGallery when click to image if BlockImageGalleryDialogContext context has value is "true"', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, container, user;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp({
                        props: { attributeValues: imageAttributeValues },
                        blockDialogContextValue: true
                    }), container = _a.container, user = _a.user;
                    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    return [4 /*yield*/, user.click(screen.getAllByTestId('image-content')[0])];
                case 1:
                    _b.sent();
                    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    describe('actions', function () {
        it('should call actions from Image component props', function () { return __awaiter(void 0, void 0, void 0, function () {
            var _a, container, user, clipboardText;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = setUp({ props: { attributeValues: imageAttributeValues, overlay: true } }), container = _a.container, user = _a.user;
                        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
                        act(function () {
                            resizeObserver.resize();
                        });
                        return [4 /*yield*/, user.click(screen.getAllByTestId('download')[0])];
                    case 1:
                        _b.sent();
                        expect(downloadImagesByURLs).toHaveBeenCalledWith([imageAttributeValues[0].uri]);
                        return [4 /*yield*/, user.click(screen.getAllByTestId('share')[0])];
                    case 2:
                        _b.sent();
                        return [4 /*yield*/, navigator.clipboard.readText()];
                    case 3:
                        clipboardText = _b.sent();
                        expect(clipboardText).toBe(imageAttributeValues[0].uri);
                        return [4 /*yield*/, user.click(screen.getAllByTestId('set-as-default')[0])];
                    case 4:
                        _b.sent();
                        expect(insertDefaultImageByAttrUri).toHaveBeenCalledWith('entities/123', imageAttributeValues[0].uri);
                        expect(defaultMdmActions.setDefaultProfilePicForEntity).toHaveBeenCalledWith(imageAttributeValues[0]);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should call actions from ImageAttributesGallery props', function () { return __awaiter(void 0, void 0, void 0, function () {
            var _a, container, user, clipboardText;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = setUp({ props: { attributeValues: imageAttributeValues } }), container = _a.container, user = _a.user;
                        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
                        act(function () {
                            resizeObserver.resize();
                        });
                        return [4 /*yield*/, user.click(screen.getAllByTestId('image-content')[0])];
                    case 1:
                        _b.sent();
                        expect(screen.getByRole('dialog')).toBeInTheDocument();
                        return [4 /*yield*/, user.click(screen.getByText('Set as default'))];
                    case 2:
                        _b.sent();
                        expect(insertDefaultImageByAttrUri).toHaveBeenCalledWith('entities/123', imageAttributeValues[0].uri);
                        expect(defaultMdmActions.setDefaultProfilePicForEntity).toHaveBeenCalledWith(imageAttributeValues[0]);
                        return [4 /*yield*/, user.click(screen.getByLabelText('Copy link'))];
                    case 3:
                        _b.sent();
                        return [4 /*yield*/, navigator.clipboard.readText()];
                    case 4:
                        clipboardText = _b.sent();
                        expect(clipboardText).toBe('/test.jpg');
                        return [4 /*yield*/, user.click(screen.getByLabelText('Download selected items'))];
                    case 5:
                        _b.sent();
                        expect(downloadImagesByURLs).toHaveBeenCalledWith(['/test.jpg']);
                        return [2 /*return*/];
                }
            });
        }); });
        it('should call "requestNextPageOfAttributeValues" prop if "paging" prop is defined', function () {
            var requestNextPageOfAttributeValues = jest.fn();
            var props = __assign(__assign({}, defaultProps), { attributeValues: imageAttributeValues, requestNextPageOfAttributeValues: requestNextPageOfAttributeValues, paging: { totalValues: 10, totalOvValues: 10 }, parentUri: 'entity/1' });
            setUp({ props: props });
            expect(requestNextPageOfAttributeValues).toHaveBeenCalledWith({
                parentUri: 'entity/1',
                attributeTypeUri: defaultProps.attributeType.uri,
                attributeTypeName: defaultProps.attributeType.name,
                values: [],
                defaultMaxValues: 10
            });
        });
        it('should use showNonOv for determining defaultMaxValues param of requestNextPageOfAttributeValues', function () {
            var requestNextPageOfAttributeValues = jest.fn();
            var props = __assign(__assign({}, defaultProps), { attributeValues: imageAttributeValues, requestNextPageOfAttributeValues: requestNextPageOfAttributeValues, paging: { totalValues: 10, totalOvValues: 8 }, parentUri: 'entity/1', showNonOv: true });
            setUp({ props: props });
            expect(requestNextPageOfAttributeValues).toHaveBeenCalledWith({
                parentUri: 'entity/1',
                attributeTypeUri: defaultProps.attributeType.uri,
                attributeTypeName: defaultProps.attributeType.name,
                values: [],
                defaultMaxValues: 8
            });
        });
    });
    it('should calculate max items if countFixedItems more than 0', function () { return __awaiter(void 0, void 0, void 0, function () {
        var container;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    container = setUp({
                        props: { attributeValues: imageAttributeValues, countFixedItems: 1 },
                        mdmValues: { mode: Mode.Editing }
                    }).container;
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    expect(screen.getAllByTestId('image')).toHaveLength(3);
                    expect(screen.queryByTestId('more-image-button')).not.toBeInTheDocument();
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
                    act(function () {
                        resizeObserver.resize(container);
                    });
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+2'); })];
                case 1:
                    _a.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(1);
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 239 } });
                    act(function () {
                        resizeObserver.resize(container);
                    });
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+3'); })];
                case 2:
                    _a.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(1);
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 240 } });
                    act(function () {
                        resizeObserver.resize(container);
                    });
                    return [4 /*yield*/, waitFor(function () { return expect(screen.getByTestId('more-image-button')).toHaveTextContent('+2'); })];
                case 3:
                    _a.sent();
                    expect(screen.getAllByTestId('image')).toHaveLength(1);
                    return [2 /*return*/];
            }
        });
    }); });
});
