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, fireEvent, render, screen, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Mode, insertDefaultImageByAttrUri, uploadImage } from '@reltio/mdm-sdk';
import { ThemeProvider } from '@mui/styles';
import { createTheme } from '@mui/material/styles';
import { theme } from '../constants';
import { downloadImagesByURLs } from '../ImageAttributesLine/helpers';
import { attributeType, imageAttributeValues } from '../ImageAttributesLine/imageAttributeValues.test-data';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
import { ImageAttributesLineEditor } from './ImageAttributesLineEditor';
jest.unmock('@mui/styles');
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { insertDefaultImageByAttrUri: jest.fn().mockReturnValue({ then: function (f) { return f({ status: 'success' }); } }), uploadImage: jest.fn() })); });
jest.mock('../ImageAttributesLine/helpers', function () { return ({
    downloadImagesByURLs: jest.fn()
}); });
var entity = { uri: 'entities/1Rd2I9Mt' };
var modifiedEntities = {
    'entities/1Rd2I9Mt': {
        defaultProfilePic: 'entities/1Rd2I9Mt/attributes/ImageGallery/39V5GWJZv',
        uri: 'entities/01eLeVm',
        type: 'configuration/entityTypes/HCP'
    }
};
var defaultMdmValues = {
    entity: entity,
    modifiedEntities: modifiedEntities,
    mode: Mode.Viewing,
    imageServicePath: '',
    environment: '',
    tenant: { id: 'tenant', name: 'tenant' }
};
var defaultMdmActions = {
    setDefaultProfilePicForModifiedEntity: jest.fn(),
    setDefaultProfilePicForEntity: jest.fn()
};
var onChangeAttribute = jest.fn();
var onDeleteAttribute = jest.fn();
var defaultProps = {
    attributeValues: imageAttributeValues,
    attributeType: attributeType,
    parentUri: 'entities/01eLeVm',
    onDeleteAttribute: onDeleteAttribute,
    onChangeAttribute: onChangeAttribute
};
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;
    var user = userEvent.setup({ skipHover: true });
    var Providers = function (_a) {
        var children = _a.children;
        return (React.createElement(MdmModuleProvider, { values: __assign(__assign({}, defaultMdmValues), mdmValues), actions: __assign(__assign({}, defaultMdmActions), mdmActions) },
            React.createElement(ThemeProvider, { theme: createTheme(theme) }, children)));
    };
    return __assign({ user: user }, render(React.createElement(ImageAttributesLineEditor, __assign({}, defaultProps, props)), { wrapper: Providers }));
};
describe('ImageAttributesLineEditor edit tests', function () {
    var resizeObserver = mockResizeObserver();
    beforeEach(function () {
        jest.clearAllMocks();
    });
    it('should render main parts', function () {
        setUp();
        var container = screen.getByTestId('image-line-edit-mode');
        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
        act(function () {
            resizeObserver.resize();
        });
        expect(screen.getByTestId('reltio-upload-image-button')).toBeInTheDocument();
        var images = screen.getAllByRole('img', { hidden: true });
        expect(images).toHaveLength(3);
    });
    it('should provide custom sizeImage to Image and ImageAttributesLine', function () {
        var imageSize = { imageMargin: 40, imageWidth: 11, imageHeight: 3 };
        setUp({ props: { imageSize: imageSize } });
        var container = screen.getByTestId('image-line-edit-mode');
        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 300 } });
        act(function () {
            resizeObserver.resize();
        });
        var images = screen.getAllByRole('img', { hidden: true });
        expect(images).toHaveLength(3);
        var computedStyles = getComputedStyle(images[0]);
        expect(computedStyles.width).toBe('11px');
        expect(computedStyles.height).toBe('3px');
    });
    it('should render images', function () {
        setUp({ props: { attributeValues: imageAttributeValues } });
        var container = screen.getByTestId('image-line-edit-mode');
        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
        act(function () {
            resizeObserver.resize();
        });
        var images = screen.getAllByRole('img', { hidden: true });
        expect(images).toHaveLength(3);
        expect(images[0]).toHaveAttribute('src', '/test.jpg');
        expect(images[1]).toHaveAttribute('src', '/test2.jpg');
        expect(images[2]).toHaveAttribute('src', '/wrong.jpg');
    });
    it('should open gallery dialog on image overlay click', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, container;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({ props: { attributeValues: imageAttributeValues } }).user;
                    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
                    container = screen.getByTestId('image-line-edit-mode');
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    return [4 /*yield*/, user.click(screen.getAllByRole('img', { hidden: true })[0])];
                case 1:
                    _a.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('a')).toHaveAttribute('href', '/test.jpg');
                    return [4 /*yield*/, user.click(screen.getByLabelText('Close'))];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, waitForElementToBeRemoved(screen.queryByRole('dialog'))];
                case 3:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call image overlay actions', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, container, clipboardText;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({ props: { attributeValues: imageAttributeValues, overlay: true } }).user;
                    container = screen.getByTestId('image-line-edit-mode');
                    resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                    act(function () {
                        resizeObserver.resize();
                    });
                    fireEvent.load(screen.getAllByRole('img', { hidden: true })[0]);
                    return [4 /*yield*/, user.hover(screen.getByTestId('image-actions-overlay'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByTestId('download-button'))];
                case 2:
                    _a.sent();
                    expect(downloadImagesByURLs).toHaveBeenCalledWith(['/test.jpg']);
                    return [4 /*yield*/, user.click(screen.getByTestId('image-overlay-actions'))];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('Share link'))];
                case 4:
                    _a.sent();
                    return [4 /*yield*/, navigator.clipboard.readText()];
                case 5:
                    clipboardText = _a.sent();
                    expect(clipboardText).toBe('/test.jpg');
                    return [4 /*yield*/, user.click(screen.getByTestId('image-overlay-actions'))];
                case 6:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('Set as default'))];
                case 7:
                    _a.sent();
                    expect(insertDefaultImageByAttrUri).toHaveBeenCalledWith('entities/1Rd2I9Mt', imageAttributeValues[0].uri);
                    expect(defaultMdmActions.setDefaultProfilePicForEntity).toHaveBeenCalledWith(imageAttributeValues[0]);
                    return [4 /*yield*/, user.click(screen.getByTestId('image-overlay-actions'))];
                case 8:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('Delete'))];
                case 9:
                    _a.sent();
                    expect(onDeleteAttribute).toHaveBeenCalledWith({
                        uri: imageAttributeValues[0].uri,
                        attributeType: defaultProps.attributeType
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should open and close UploadImageDialog by clicking on .uploadContainer', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, backdrop;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
                    return [4 /*yield*/, user.click(screen.getByTestId('reltio-upload-image-button'))];
                case 1:
                    _a.sent();
                    expect(screen.getByRole('dialog')).toBeInTheDocument();
                    expect(screen.getByText('Add new image')).toBeInTheDocument();
                    backdrop = screen.getAllByRole('presentation')[0].firstChild;
                    return [4 /*yield*/, user.click(backdrop)];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, waitForElementToBeRemoved(screen.queryByRole('dialog'))];
                case 3:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
    describe('onChangeAttribute test', function () {
        it('should add images to globalState with imageProps', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, uploadImageDialog;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        uploadImage.mockResolvedValue({
                            Url: 'https://s3.amazonaws.com/reltio.qa.ih/sourcenew/hc3IZh8C1ixGWpmRPr54HufUd.png',
                            UrlThumbnail: 'https://s3.amazonaws.com/reltio.qa.ih/thumbnailInew/oLd1Fs5Sh2SVHHHV7uyHFZhsi.png',
                            CdnUrlThumbnail: 'https://s3.amazonaws.com/reltio.qa.ih/thumbnailInew/oLd1Fs5Sh2SVHHHV7uyHFZhsi.png',
                            Width: '990',
                            Height: '946',
                            Size: '114373',
                            MimeType: 'image/png',
                            CreationTimestamp: 1734017226633
                        });
                        user = setUp().user;
                        return [4 /*yield*/, user.click(screen.getByTestId('reltio-upload-image-button'))];
                    case 1:
                        _a.sent();
                        expect(screen.getByRole('dialog')).toBeInTheDocument();
                        uploadImageDialog = screen.getByTestId('upload-image-button');
                        expect(uploadImageDialog).toBeInTheDocument();
                        return [4 /*yield*/, user.upload(uploadImageDialog, new File(['test'], 'test.png', { type: 'image/png' }))];
                    case 2:
                        _a.sent();
                        expect(onChangeAttribute).toHaveBeenCalledWith({
                            attributeType: attributeType,
                            uri: expect.any(String),
                            value: {
                                CdnUrlThumbnail: [
                                    {
                                        ov: true,
                                        type: 'configuration/entityTypes/Series/attributes/ImageGallery/attributes/CdnUrlThumbnail',
                                        uri: expect.any(String),
                                        value: 'https://s3.amazonaws.com/reltio.qa.ih/thumbnailInew/oLd1Fs5Sh2SVHHHV7uyHFZhsi.png'
                                    }
                                ],
                                Url: [
                                    {
                                        ov: true,
                                        type: 'configuration/entityTypes/Series/attributes/ImageGallery/attributes/Url',
                                        uri: expect.any(String),
                                        value: 'https://s3.amazonaws.com/reltio.qa.ih/sourcenew/hc3IZh8C1ixGWpmRPr54HufUd.png'
                                    }
                                ],
                                UrlThumbnail: [
                                    {
                                        ov: true,
                                        type: 'configuration/entityTypes/Series/attributes/ImageGallery/attributes/UrlThumbnail',
                                        uri: expect.any(String),
                                        value: 'https://s3.amazonaws.com/reltio.qa.ih/thumbnailInew/oLd1Fs5Sh2SVHHHV7uyHFZhsi.png'
                                    }
                                ]
                            }
                        });
                        return [4 /*yield*/, waitForElementToBeRemoved(screen.queryByRole('dialog'))];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); });
    });
    describe('handleDeleteAttribute test', function () {
        it('should delete and choose another defaultPic', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, container;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = setUp({ props: { attributeValues: imageAttributeValues, overlay: true } }).user;
                        container = screen.getByTestId('image-line-edit-mode');
                        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                        act(function () {
                            resizeObserver.resize();
                        });
                        fireEvent.load(screen.getAllByRole('img', { hidden: true })[0]);
                        return [4 /*yield*/, user.hover(screen.getByTestId('image-actions-overlay'))];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, user.click(screen.getByTestId('image-overlay-actions'))];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, user.click(screen.getByText('Delete'))];
                    case 3:
                        _a.sent();
                        expect(defaultMdmActions.setDefaultProfilePicForModifiedEntity).toHaveBeenCalledWith({
                            entityUri: 'entities/1Rd2I9Mt',
                            value: imageAttributeValues[1]
                        });
                        expect(onDeleteAttribute).toHaveBeenCalledWith({
                            uri: imageAttributeValues[0].uri,
                            attributeType: defaultProps.attributeType
                        });
                        return [2 /*return*/];
                }
            });
        }); });
        it('should not choose another defaultPic if non-default deleted', function () { return __awaiter(void 0, void 0, void 0, function () {
            var user, container;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        user = setUp({ props: { attributeValues: imageAttributeValues, overlay: true } }).user;
                        container = screen.getByTestId('image-line-edit-mode');
                        resizeObserver.mockElementSize(container, { contentBoxSize: { inlineSize: 600 } });
                        act(function () {
                            resizeObserver.resize();
                        });
                        fireEvent.load(screen.getAllByRole('img', { hidden: true })[1]);
                        return [4 /*yield*/, user.hover(screen.getByTestId('image-actions-overlay'))];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, user.click(screen.getByTestId('image-overlay-actions'))];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, user.click(screen.getByText('Delete'))];
                    case 3:
                        _a.sent();
                        expect(defaultMdmActions.setDefaultProfilePicForModifiedEntity).not.toHaveBeenCalled();
                        expect(onDeleteAttribute).toHaveBeenCalledWith({
                            uri: imageAttributeValues[1].uri,
                            attributeType: defaultProps.attributeType
                        });
                        return [2 /*return*/];
                }
            });
        }); });
    });
});
