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 { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ErrorType, MetadataPermissions, Mode } from '@reltio/mdm-sdk';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
import { ScrollToElementContext, ScrollType } from '../contexts/ScrollToElementContext';
import { nestedAttributeType } from './nestedAttrType.test-data';
import { nestedAttributeValue } from './nestedAttrValue.test-data';
import EditModeComplexAttribute from './EditModeComplexAttribute';
var defaultMdmValues = { dependentLookups: { editors: {}, structure: {}, initedTypeUris: [] } };
var defaultProps = {
    metadata: {
        entityTypes: [],
        relationTypes: [
            {
                uri: 'configuration/relationTypes/InternalHCPtoHCP',
                label: 'HCP to HCP',
                attributes: [nestedAttributeType]
            }
        ]
    },
    label: 'Label!!!',
    attributeType: nestedAttributeType,
    attributeValue: nestedAttributeValue,
    attributeTypesList: nestedAttributeType.attributes,
    mode: Mode.Editing,
    onAddAttributes: jest.fn(),
    onDeleteAttribute: jest.fn(),
    onChangeAttribute: jest.fn(),
    additionalControlsRenderer: jest.fn(function (_a) {
        var attributeType = _a.attributeType;
        return React.createElement("div", null,
            "Additional Controls ",
            attributeType.label);
    })
};
var defaultScrollToElementContextValue = {
    element: null,
    highlightError: jest.fn(),
    type: ScrollType.Error,
    scrollIntoRef: 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.scrollToElementContextValue, scrollToElementContextValue = _e === void 0 ? defaultScrollToElementContextValue : _e;
    var user = userEvent.setup();
    var Providers = function (_a) {
        var children = _a.children;
        return (React.createElement(MdmModuleProvider, { values: mdmValues }, children));
    };
    var result = render(React.createElement(ScrollToElementContext.Provider, { value: scrollToElementContextValue },
        React.createElement(EditModeComplexAttribute, __assign({}, props))), { wrapper: Providers });
    var rerender = function (_a) {
        var newProps = _a.props, newScrollToElementContextValue = _a.scrollToElementContextValue;
        return result.rerender(React.createElement(ScrollToElementContext.Provider, { value: __assign(__assign({}, scrollToElementContextValue), newScrollToElementContextValue) },
            React.createElement(EditModeComplexAttribute, __assign({}, props, newProps))));
    };
    return __assign(__assign({}, result), { rerender: rerender, user: user });
};
describe('Edit mode complex attribute tests', function () {
    afterEach(function () {
        jest.clearAllMocks();
    });
    it('should render expand button and label', function () {
        var props = __assign(__assign({}, defaultProps), { onDeleteAttribute: undefined });
        setUp({ props: props });
        screen.getByTestId('arrow-expand-button');
        screen.getByText('Label!!!');
        expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        expect(screen.queryByTestId('reltio-delete-complex-attribute-button')).not.toBeInTheDocument();
        expect(screen.queryByText('Create attribute')).not.toBeInTheDocument();
    });
    it('should render lazy variant of control if lazy prop is true', function () {
        var props = __assign(__assign({}, defaultProps), { lazy: true });
        setUp({ props: props });
        expect(screen.queryByTestId('reltio-edit-mode-complex-attribute')).not.toBeInTheDocument();
        screen.getByText('Create attribute');
    });
    it('should render delete button if onDeleteAttribute prop is specified', function () {
        setUp();
        screen.getByTestId('reltio-delete-complex-attribute-button');
    });
    it('should not render delete button if hideDeleteButton prop is true', function () {
        var props = __assign(__assign({}, defaultProps), { hideDeleteButton: true });
        setUp({ props: props });
        expect(screen.queryByTestId('reltio-delete-complex-attribute-button')).not.toBeInTheDocument();
    });
    it('should not render delete button if there are no DELETE permissions', function () {
        var attributeType = __assign(__assign({}, nestedAttributeType), { access: [MetadataPermissions.READ, MetadataPermissions.UPDATE] });
        var props = __assign(__assign({}, defaultProps), { attributeType: attributeType });
        setUp({ props: props });
        expect(screen.queryByTestId('reltio-delete-complex-attribute-button')).not.toBeInTheDocument();
    });
    it('should call onDeleteAttribute prop with attributeType and value uri after click on delete button', 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.getByTestId('reltio-delete-complex-attribute-button'))];
                case 1:
                    _a.sent();
                    expect(defaultProps.onDeleteAttribute).toHaveBeenCalledWith({
                        uri: defaultProps.attributeValue.uri,
                        attributeType: defaultProps.attributeType,
                        attributeValue: defaultProps.attributeValue
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render additional controls if additionalControlsRenderer prop is specified', function () {
        setUp();
        screen.getByText('Additional Controls Additional Attributes');
        expect(defaultProps.additionalControlsRenderer).toHaveBeenCalledWith({
            attributeType: defaultProps.attributeType,
            attributeValue: defaultProps.attributeValue
        });
    });
    it('should render EditModeAttributesList after click on expand button', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { children: React.createElement("div", null, "Children") });
                    user = setUp({ props: props }).user;
                    expect(screen.queryByText('More attributes')).not.toBeInTheDocument();
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    return [4 /*yield*/, user.click(screen.getByTestId('arrow-expand-button'))];
                case 1:
                    _a.sent();
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
                    screen.getByText('More attributes');
                    screen.getByText('Children');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render EditModeAttributesList if expand prop was passed', function () {
        var props = __assign(__assign({}, defaultProps), { expanded: true, children: React.createElement("div", null, "Children") });
        setUp({ props: props });
        expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
        screen.getByText('More attributes');
        screen.getByText('Children');
    });
    it('should be expanded by default for new attributes', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { attributeValue: __assign(__assign({}, nestedAttributeValue), { uri: 'relations/sIeHttl/attributes/AdditionalAttributes/uri$$123' }), children: React.createElement("div", null, "Children") });
                    user = setUp({ props: props }).user;
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
                    screen.getByText('More attributes');
                    screen.getByText('Children');
                    return [4 /*yield*/, user.click(screen.getAllByTestId('arrow-expand-button')[0])];
                case 1:
                    _a.sent();
                    expect(screen.queryByText('More attributes')).not.toBeInTheDocument();
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render attributes correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, complexAttributeActions, attributeActions, complexAttributeLabels, attributeTitles, attributeValues;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp().user;
                    return [4 /*yield*/, user.click(screen.getAllByTestId('arrow-expand-button')[0])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getAllByTestId('arrow-expand-button')[1])];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getAllByTestId('arrow-expand-button')[2])];
                case 3:
                    _a.sent();
                    complexAttributeActions = screen.getAllByTestId('reltio-complex-attribute-actions');
                    expect(complexAttributeActions).toHaveLength(3);
                    expect(complexAttributeActions[0]).toHaveTextContent('Additional Controls Additional Attributes');
                    expect(complexAttributeActions[1]).toHaveTextContent('Additional Controls Sub Nested');
                    expect(complexAttributeActions[2]).toHaveTextContent('Additional Controls Sub Sub Nested');
                    attributeActions = screen.getAllByTestId('reltio-attribute-actions');
                    expect(attributeActions).toHaveLength(1);
                    expect(attributeActions[0]).toHaveTextContent('Additional Controls Attribute Value');
                    complexAttributeLabels = screen.getAllByTestId('reltio-attribute-complex-label');
                    expect(complexAttributeLabels).toHaveLength(3);
                    expect(complexAttributeLabels[0]).toHaveTextContent('Label!!!');
                    expect(complexAttributeLabels[1]).toHaveTextContent('<No label>');
                    expect(complexAttributeLabels[2]).toHaveTextContent('<No label>');
                    attributeTitles = screen.getAllByTestId('reltio-attribute-label');
                    expect(attributeTitles).toHaveLength(3);
                    expect(attributeTitles[0]).toHaveTextContent('Sub Nested');
                    expect(attributeTitles[1]).toHaveTextContent('Sub Sub Nested');
                    expect(attributeTitles[2]).toHaveTextContent('Attribute Value');
                    attributeValues = screen.getAllByTestId('reltio-attribute-value');
                    expect(attributeValues).toHaveLength(1);
                    expect(within(attributeValues[0]).getByRole('textbox')).toHaveValue('12321');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onDeleteAttribute prop with deep nested attributeType and value uri after click on delete button in deep nested', 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.getAllByTestId('arrow-expand-button')[0])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getAllByTestId('arrow-expand-button')[1])];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getAllByTestId('arrow-expand-button')[2])];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getAllByTestId('reltio-delete-complex-attribute-button')[2])];
                case 4:
                    _a.sent();
                    expect(defaultProps.onDeleteAttribute).toHaveBeenCalledWith({
                        uri: defaultProps.attributeValue.value.SubNested[0].value.SubSubNested[0].uri,
                        attributeType: defaultProps.attributeType.attributes[0].attributes[0],
                        attributeValue: defaultProps.attributeValue.value.SubNested[0].value.SubSubNested[0]
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not show error message if error prop is not specified', function () {
        setUp();
        expect(screen.queryByTestId('error-message')).not.toBeInTheDocument();
    });
    it('should show error message if ownError prop is specified', function () {
        var props = __assign(__assign({}, defaultProps), { ownError: {
                type: ErrorType.invalid,
                message: 'error description',
                attributeTypeUri: 'any1',
                parentUri: 'any2',
                uri: 'any3'
            } });
        setUp({ props: props });
        expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        expect(screen.getByTestId('error-message')).toHaveTextContent(props.ownError.message);
    });
    it('should become expanded and show special error message if errors props contains descendants errors', function () {
        var props = __assign(__assign({}, defaultProps), { errors: [] });
        var rerender = setUp({ props: props }).rerender;
        expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        expect(screen.queryByTestId('error-message')).not.toBeInTheDocument();
        rerender({
            props: {
                errors: [
                    {
                        parentUri: 'relations/sIeHttl/attributes/AdditionalAttributes/2zoXFFwDl/SubNested/gdggfgfgdf/SubSubNested/1',
                        uri: '',
                        attributeTypeUri: 'configuration/relationTypes/InternalHCPtoHCP/attributes/AdditionalAttributes/attributes/SubNested/attributes/SubSubNested/attributes/AttributeValue',
                        message: 'Attribute is required',
                        type: ErrorType.missed
                    }
                ]
            }
        });
        expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
        expect(screen.getByTestId('error-message')).toHaveTextContent('Has an incorrect value');
    });
    it('should become collapsed after setting "state" prop to "deleted"', function () { return __awaiter(void 0, void 0, void 0, function () {
        var _a, user, rerender;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = setUp(), user = _a.user, rerender = _a.rerender;
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    expect(screen.getByTestId('reltio-attribute-complex-label')).not.toHaveClass('deleted');
                    expect(screen.getByTestId('arrow-expand-button')).not.toBeDisabled();
                    screen.getByTestId('reltio-delete-complex-attribute-button');
                    return [4 /*yield*/, user.click(screen.getByTestId('arrow-expand-button'))];
                case 1:
                    _b.sent();
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
                    rerender({ props: { state: 'deleted' } });
                    expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    expect(screen.getByTestId('reltio-attribute-complex-label')).toHaveClass('deleted');
                    expect(screen.getByTestId('arrow-expand-button')).toBeDisabled();
                    expect(screen.queryByTestId('reltio-delete-complex-attribute-button')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render "edited" badge after setting "state" prop to "edited"', function () {
        var rerender = setUp().rerender;
        expect(screen.queryByText('(edited)')).not.toBeInTheDocument();
        rerender({ props: { state: 'edited' } });
        screen.getByText('(edited)');
    });
    describe('useScrollToAttributeError tests', function () {
        var fullError = {
            type: 'invalid',
            attributeTypeUri: defaultProps.attributeType.uri,
            parentUri: null,
            name: '',
            uri: defaultProps.attributeValue.uri,
            source: 'validationService',
            severity: 'ERROR'
        };
        it('should not highlight error if it have wrong uri', function () {
            var error = __assign(__assign({}, fullError), { uri: 'different' });
            var scrollToElementContextValue = __assign(__assign({}, defaultScrollToElementContextValue), { element: error });
            setUp({ scrollToElementContextValue: scrollToElementContextValue });
            expect(screen.getByTestId('reltio-edit-mode-complex-attribute')).not.toHaveClass('highlightError');
            expect(scrollToElementContextValue.scrollIntoRef).not.toHaveBeenCalled();
        });
        it('should highlight error if it have same parent uri, uri, and attribute type uri', function () {
            var scrollToElementContextValue = __assign(__assign({}, defaultScrollToElementContextValue), { element: fullError });
            setUp({ scrollToElementContextValue: scrollToElementContextValue });
            expect(screen.getByTestId('reltio-edit-mode-complex-attribute')).toHaveClass('highlightError');
            expect(scrollToElementContextValue.scrollIntoRef).toHaveBeenCalled();
        });
        it('should pass isHighlightedPath=false prop if path is not contains uri', function () {
            var rerender = setUp().rerender;
            expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
            var error = __assign(__assign({}, fullError), { path: [] });
            var scrollToElementContextValue = __assign(__assign({}, defaultScrollToElementContextValue), { element: error });
            rerender({ scrollToElementContextValue: scrollToElementContextValue });
            expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        });
        it('should pass isHighlightedPath=true prop if path is contains uri', function () {
            var rerender = setUp().rerender;
            expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
            var error = __assign(__assign({}, fullError), { path: [{ value: defaultProps.attributeValue }] });
            var scrollToElementContextValue = __assign(__assign({}, defaultScrollToElementContextValue), { element: error });
            rerender({ scrollToElementContextValue: scrollToElementContextValue });
            expect(screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
        });
    });
});
