"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 react_2 = require("@testing-library/react");
var user_event_1 = __importDefault(require("@testing-library/user-event"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
var ScrollToElementContext_1 = require("../contexts/ScrollToElementContext");
var nestedAttrType_test_data_1 = require("./nestedAttrType.test-data");
var nestedAttrValue_test_data_1 = require("./nestedAttrValue.test-data");
var EditModeComplexAttribute_1 = __importDefault(require("./EditModeComplexAttribute"));
var defaultMdmValues = { dependentLookups: { editors: {}, structure: {}, initedTypeUris: [] } };
var defaultProps = {
    metadata: {
        entityTypes: [],
        relationTypes: [
            {
                uri: 'configuration/relationTypes/InternalHCPtoHCP',
                label: 'HCP to HCP',
                attributes: [nestedAttrType_test_data_1.nestedAttributeType]
            }
        ]
    },
    label: 'Label!!!',
    attributeType: nestedAttrType_test_data_1.nestedAttributeType,
    attributeValue: nestedAttrValue_test_data_1.nestedAttributeValue,
    attributeTypesList: nestedAttrType_test_data_1.nestedAttributeType.attributes,
    mode: mdm_sdk_1.Mode.Editing,
    onAddAttributes: jest.fn(),
    onDeleteAttribute: jest.fn(),
    onChangeAttribute: jest.fn(),
    additionalControlsRenderer: jest.fn(function (_a) {
        var attributeType = _a.attributeType;
        return react_1.default.createElement("div", null,
            "Additional Controls ",
            attributeType.label);
    })
};
var defaultScrollToElementContextValue = {
    element: null,
    highlightError: jest.fn(),
    type: ScrollToElementContext_1.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 = user_event_1.default.setup();
    var Providers = function (_a) {
        var children = _a.children;
        return (react_1.default.createElement(MdmModuleContext_1.MdmModuleProvider, { values: mdmValues }, children));
    };
    var result = (0, react_2.render)(react_1.default.createElement(ScrollToElementContext_1.ScrollToElementContext.Provider, { value: scrollToElementContextValue },
        react_1.default.createElement(EditModeComplexAttribute_1.default, __assign({}, props))), { wrapper: Providers });
    var rerender = function (_a) {
        var newProps = _a.props, newScrollToElementContextValue = _a.scrollToElementContextValue;
        return result.rerender(react_1.default.createElement(ScrollToElementContext_1.ScrollToElementContext.Provider, { value: __assign(__assign({}, scrollToElementContextValue), newScrollToElementContextValue) },
            react_1.default.createElement(EditModeComplexAttribute_1.default, __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 });
        react_2.screen.getByTestId('arrow-expand-button');
        react_2.screen.getByText('Label!!!');
        expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        expect(react_2.screen.queryByTestId('reltio-delete-complex-attribute-button')).not.toBeInTheDocument();
        expect(react_2.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(react_2.screen.queryByTestId('reltio-edit-mode-complex-attribute')).not.toBeInTheDocument();
        react_2.screen.getByText('Create attribute');
    });
    it('should render delete button if onDeleteAttribute prop is specified', function () {
        setUp();
        react_2.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(react_2.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({}, nestedAttrType_test_data_1.nestedAttributeType), { access: [mdm_sdk_1.MetadataPermissions.READ, mdm_sdk_1.MetadataPermissions.UPDATE] });
        var props = __assign(__assign({}, defaultProps), { attributeType: attributeType });
        setUp({ props: props });
        expect(react_2.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(react_2.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();
        react_2.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_1.default.createElement("div", null, "Children") });
                    user = setUp({ props: props }).user;
                    expect(react_2.screen.queryByText('More attributes')).not.toBeInTheDocument();
                    expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    return [4 /*yield*/, user.click(react_2.screen.getByTestId('arrow-expand-button'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
                    react_2.screen.getByText('More attributes');
                    react_2.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_1.default.createElement("div", null, "Children") });
        setUp({ props: props });
        expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
        react_2.screen.getByText('More attributes');
        react_2.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({}, nestedAttrValue_test_data_1.nestedAttributeValue), { uri: 'relations/sIeHttl/attributes/AdditionalAttributes/uri$$123' }), children: react_1.default.createElement("div", null, "Children") });
                    user = setUp({ props: props }).user;
                    expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
                    react_2.screen.getByText('More attributes');
                    react_2.screen.getByText('Children');
                    return [4 /*yield*/, user.click(react_2.screen.getAllByTestId('arrow-expand-button')[0])];
                case 1:
                    _a.sent();
                    expect(react_2.screen.queryByText('More attributes')).not.toBeInTheDocument();
                    expect(react_2.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(react_2.screen.getAllByTestId('arrow-expand-button')[0])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getAllByTestId('arrow-expand-button')[1])];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getAllByTestId('arrow-expand-button')[2])];
                case 3:
                    _a.sent();
                    complexAttributeActions = react_2.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 = react_2.screen.getAllByTestId('reltio-attribute-actions');
                    expect(attributeActions).toHaveLength(1);
                    expect(attributeActions[0]).toHaveTextContent('Additional Controls Attribute Value');
                    complexAttributeLabels = react_2.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 = react_2.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 = react_2.screen.getAllByTestId('reltio-attribute-value');
                    expect(attributeValues).toHaveLength(1);
                    expect((0, react_2.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(react_2.screen.getAllByTestId('arrow-expand-button')[0])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getAllByTestId('arrow-expand-button')[1])];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getAllByTestId('arrow-expand-button')[2])];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.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(react_2.screen.queryByTestId('error-message')).not.toBeInTheDocument();
    });
    it('should show error message if ownError prop is specified', function () {
        var props = __assign(__assign({}, defaultProps), { ownError: {
                type: mdm_sdk_1.ErrorType.invalid,
                message: 'error description',
                attributeTypeUri: 'any1',
                parentUri: 'any2',
                uri: 'any3'
            } });
        setUp({ props: props });
        expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        expect(react_2.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(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
        expect(react_2.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: mdm_sdk_1.ErrorType.missed
                    }
                ]
            }
        });
        expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
        expect(react_2.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(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    expect(react_2.screen.getByTestId('reltio-attribute-complex-label')).not.toHaveClass('deleted');
                    expect(react_2.screen.getByTestId('arrow-expand-button')).not.toBeDisabled();
                    react_2.screen.getByTestId('reltio-delete-complex-attribute-button');
                    return [4 /*yield*/, user.click(react_2.screen.getByTestId('arrow-expand-button'))];
                case 1:
                    _b.sent();
                    expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
                    rerender({ props: { state: 'deleted' } });
                    expect(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(1);
                    expect(react_2.screen.getByTestId('reltio-attribute-complex-label')).toHaveClass('deleted');
                    expect(react_2.screen.getByTestId('arrow-expand-button')).toBeDisabled();
                    expect(react_2.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(react_2.screen.queryByText('(edited)')).not.toBeInTheDocument();
        rerender({ props: { state: 'edited' } });
        react_2.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(react_2.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(react_2.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(react_2.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(react_2.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(react_2.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(react_2.screen.getAllByTestId('reltio-edit-mode-complex-attribute')).toHaveLength(2);
        });
    });
});
