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 { adjust, assoc } from 'ramda';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
import { ActivenessAttrTypes, Mode } from '@reltio/mdm-sdk';
import { PinnedAttributesContext } from '../contexts/PinnedAttributesContext';
import { attributesList } from './attributes.test-data';
import EditModeAttributesList from './EditModeAttributesList';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
var defaultAttributes = {
    Role: [
        {
            ov: true,
            type: 'configuration/relationTypes/knowledge/attributes/Role',
            uri: 'relations/8908/Role',
            value: ''
        },
        {
            ov: true,
            type: 'configuration/relationTypes/knowledge/attributes/Role',
            uri: 'relations/8909/Role',
            value: 'Some role'
        }
    ],
    Name: [
        {
            ov: true,
            type: 'configuration/relationTypes/knowledge/attributes/Name',
            uri: 'relations/8808/Name',
            value: ''
        }
    ],
    LastName: [
        {
            ov: true,
            type: 'configuration/relationTypes/knowledge/attributes/LastName',
            uri: 'relations/7808/LastName',
            value: ''
        }
    ],
    paging: {
        'configuration/relationTypes/knowledge/attributes/Role': {
            totalOvValues: 4,
            totalValues: 4
        }
    }
};
var defaultEntity = { uri: 'entities/xT3HJZ7', type: 'configuration/entityTypes/HCP', attributes: defaultAttributes };
var defaultProps = {
    parentUri: 'entities/xT3HJZ7',
    entity: defaultEntity,
    attrTypes: attributesList,
    mode: Mode.Editing,
    showEmptyEditors: false,
    onAddAttributes: jest.fn(),
    onDeleteAttribute: jest.fn(),
    onChangeAttribute: jest.fn()
};
var dependentLookups = { editors: {}, structure: {}, initedTypeUris: [] };
var defaultMdmValues = { dependentLookups: dependentLookups };
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.pinnedAttributesContextValue, pinnedAttributesContextValue = _e === void 0 ? [] : _e;
    var user = userEvent.setup();
    var Providers = function (_a) {
        var children = _a.children;
        return (React.createElement(MdmModuleProvider, { values: mdmValues },
            React.createElement(PinnedAttributesContext.Provider, { value: pinnedAttributesContextValue },
                React.createElement(LocalizationProvider, { dateAdapter: AdapterMoment }, children))));
    };
    var result = render(React.createElement(EditModeAttributesList, __assign({}, props)), { wrapper: Providers });
    var rerender = function (newProps) {
        return result.rerender(React.createElement(EditModeAttributesList, __assign({}, props, newProps)));
    };
    return __assign(__assign({}, result), { rerender: rerender, user: user });
};
describe('Edit mode attributes list tests', function () {
    afterEach(function () {
        jest.clearAllMocks();
    });
    it('should render button with label and not hidden/required pagers', function () {
        setUp();
        screen.getByText('More attributes');
        var attributeLabels = screen.getAllByTestId('reltio-attribute-label');
        expect(attributeLabels).toHaveLength(3);
        expect(attributeLabels[0]).toHaveTextContent('Role');
        expect(attributeLabels[1]).toHaveTextContent('Name*');
        expect(attributeLabels[2]).toHaveTextContent('Required*');
        var attributes = screen.getAllByTestId('reltio-edit-attribute');
        expect(attributes).toHaveLength(4);
        expect(within(attributes[0]).getByRole('textbox')).toHaveValue('');
        expect(within(attributes[1]).getByRole('textbox')).toHaveValue('Some role');
        expect(within(attributes[2]).getByRole('textbox')).toHaveValue('');
        expect(within(attributes[3]).getByRole('textbox')).toHaveValue('');
    });
    it('should not add to more attr types single value types with non-empty attr value', function () { return __awaiter(void 0, void 0, void 0, function () {
        var attrTypes, props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    attrTypes = adjust(1, assoc('singleValue', true), attributesList);
                    props = __assign(__assign({}, defaultProps), { attrTypes: attrTypes });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByText('More attributes'))];
                case 1:
                    _a.sent();
                    expect(within(screen.getByRole('presentation')).queryByText('Name')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not add to more attr types single value types in showEmptyEditors mode if they did not have deletions', function () {
        var attrTypes = Object.values(ActivenessAttrTypes);
        var props = __assign(__assign({}, defaultProps), { attrTypes: attrTypes, showEmptyEditors: true });
        setUp({ props: props });
        expect(screen.queryByText('More attributes')).not.toBeInTheDocument();
    });
    it('should add to more attr types single value types in showEmptyEditors mode if they had deletions', function () { return __awaiter(void 0, void 0, void 0, function () {
        var attrTypes, props, user, menuItems;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    attrTypes = Object.values(ActivenessAttrTypes);
                    props = __assign(__assign({}, defaultProps), { attrTypes: attrTypes, showEmptyEditors: true });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getAllByTestId('reltio-delete-simple-attribute-button')[0])];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('More attributes'))];
                case 2:
                    _a.sent();
                    menuItems = screen.getAllByRole('menuitem');
                    expect(menuItems).toHaveLength(1);
                    expect(menuItems[0]).toHaveTextContent('Start date');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not render pagers for attribute type without CREATE permission', function () {
        var attrTypes = __spreadArray([], attributesList, true);
        attrTypes[0] = __assign({}, attrTypes[0]);
        attrTypes[3] = __assign({}, attrTypes[3]);
        attrTypes[0].access = ['DELETE', 'UPDATE'];
        attrTypes[3].access = ['INITIATE_CHANGE_REQUEST'];
        var props = __assign(__assign({}, defaultProps), { attrTypes: attrTypes });
        setUp({ props: props });
        expect(screen.getAllByTestId('reltio-edit-attribute')).toHaveLength(1);
    });
    it('should not render pager for not required attribute type with only ov=false values', function () {
        var attrTypes = [
            {
                label: 'Name',
                name: 'Name',
                type: 'String',
                hidden: false,
                required: false,
                uri: 'configuration/entityTypes/HCP/attributes/Name'
            }
        ];
        var entity = __assign(__assign({}, defaultEntity), { attributes: {
                Name: [
                    {
                        ov: false,
                        type: 'configuration/entityTypes/HCP/attributes/Name',
                        uri: 'entities/8808/Name',
                        value: ''
                    },
                    {
                        ov: false,
                        type: 'configuration/entityTypes/HCP/attributes/Name',
                        uri: 'entities/8808/Name1',
                        value: '1'
                    }
                ]
            } });
        var props = __assign(__assign({}, defaultProps), { entity: entity, attrTypes: attrTypes });
        setUp({ props: props });
        expect(screen.queryByTestId('reltio-edit-attribute')).not.toBeInTheDocument();
    });
    it('should render pager for not required attribute type with ov=false values if showNonOv is true', function () {
        var attrTypes = [
            {
                label: 'Name',
                name: 'Name',
                type: 'String',
                hidden: false,
                required: false,
                uri: 'configuration/entityTypes/HCP/attributes/Name'
            }
        ];
        var entity = __assign(__assign({}, defaultEntity), { attributes: {
                Name: [
                    {
                        ov: false,
                        type: 'configuration/entityTypes/HCP/attributes/Name',
                        uri: 'entities/8808/Name',
                        value: ''
                    }
                ]
            } });
        var props = __assign(__assign({}, defaultProps), { entity: entity, attrTypes: attrTypes, showNonOv: true });
        setUp({ props: props });
        expect(screen.getAllByTestId('reltio-edit-attribute')).toHaveLength(1);
    });
    it('should render pager for required attribute type with only ov=false values', function () {
        var attrTypes = [
            {
                label: 'Name',
                name: 'Name',
                type: 'String',
                hidden: false,
                required: true,
                uri: 'configuration/entityTypes/HCP/attributes/Name'
            }
        ];
        var entity = __assign(__assign({}, defaultEntity), { attributes: {
                Name: [
                    {
                        ov: false,
                        type: 'configuration/entityTypes/HCP/attributes/Name',
                        uri: 'entities/8808/Name',
                        value: ''
                    },
                    {
                        ov: false,
                        type: 'configuration/entityTypes/HCP/attributes/Name',
                        uri: 'entities/8808/Name1',
                        value: '1'
                    }
                ]
            } });
        var props = __assign(__assign({}, defaultProps), { entity: entity, attrTypes: attrTypes });
        setUp({ props: props });
        expect(screen.getAllByTestId('reltio-edit-attribute')).toHaveLength(1);
    });
    it('should not render pager for not required attribute type without values', function () {
        var attrTypes = [
            {
                label: 'Name',
                name: 'Name',
                type: 'String',
                hidden: false,
                required: false,
                uri: 'configuration/entityTypes/HCP/attributes/Name'
            }
        ];
        var entity = __assign(__assign({}, defaultEntity), { attributes: { Name: [] } });
        var props = __assign(__assign({}, defaultProps), { entity: entity, attrTypes: attrTypes });
        var rerender = setUp({ props: props }).rerender;
        expect(screen.queryByTestId('reltio-edit-attribute')).not.toBeInTheDocument();
        rerender({ entity: __assign(__assign({}, defaultEntity), { attributes: {} }) });
        expect(screen.queryByTestId('reltio-edit-attribute')).not.toBeInTheDocument();
    });
    it('should render "More attributes" button with parent if parentAttributeType is passed and creatable', function () { return __awaiter(void 0, void 0, void 0, function () {
        var parentAttributeType, attrTypes, entity, props, user, menuItems;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    parentAttributeType = {
                        label: 'Taxonomy',
                        name: 'Taxonomy',
                        type: 'Nested',
                        hidden: false,
                        uri: 'configuration/entityTypes/People/attributes/Taxonomy',
                        access: ['CREATE', 'READ', 'INITIATE_CHANGE_REQUEST', 'UPDATE']
                    };
                    attrTypes = [
                        {
                            label: 'Name',
                            name: 'Name',
                            type: 'String',
                            hidden: false,
                            required: true,
                            uri: 'configuration/entityTypes/People/attributes/Taxonomy/attributes/Name',
                            access: ['CREATE', 'READ', 'INITIATE_CHANGE_REQUEST', 'UPDATE']
                        }
                    ];
                    entity = __assign(__assign({}, defaultEntity), { attributes: { Name: [] } });
                    props = __assign(__assign({}, defaultProps), { entity: entity, attrTypes: attrTypes, parentAttributeType: parentAttributeType });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByText('More attributes'))];
                case 1:
                    _a.sent();
                    menuItems = screen.getAllByRole('menuitem');
                    expect(menuItems).toHaveLength(2);
                    expect(menuItems[0]).toHaveTextContent('Taxonomy');
                    expect(menuItems[1]).toHaveTextContent('Name*');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render "More attributes" button without parent if parentAttributeType is passed but not creatable', function () { return __awaiter(void 0, void 0, void 0, function () {
        var parentAttributeType, attrTypes, entity, props, user, menuItems;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    parentAttributeType = {
                        label: 'Taxonomy',
                        name: 'Taxonomy',
                        type: 'Nested',
                        hidden: false,
                        uri: 'configuration/entityTypes/People/attributes/Taxonomy',
                        access: ['READ', 'INITIATE_CHANGE_REQUEST', 'UPDATE']
                    };
                    attrTypes = [
                        {
                            label: 'Name',
                            name: 'Name',
                            type: 'String',
                            hidden: false,
                            required: true,
                            uri: 'configuration/entityTypes/People/attributes/Taxonomy/attributes/Name',
                            access: ['CREATE', 'READ', 'INITIATE_CHANGE_REQUEST', 'UPDATE']
                        }
                    ];
                    entity = __assign(__assign({}, defaultEntity), { attributes: { Name: [] } });
                    props = __assign(__assign({}, defaultProps), { entity: entity, attrTypes: attrTypes, parentAttributeType: parentAttributeType });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByText('More attributes'))];
                case 1:
                    _a.sent();
                    menuItems = screen.getAllByRole('menuitem');
                    expect(menuItems).toHaveLength(1);
                    expect(menuItems[0]).toHaveTextContent('Name*');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render branch decorator for "More attributes" button when drawLines prop is true', function () {
        var props = __assign(__assign({}, defaultProps), { drawLines: true });
        setUp({ props: props });
        var decorator = screen.getAllByTestId('branch-decorator')[0];
        within(decorator).getByText('More attributes');
    });
    it('should not render branch decorator for "More attributes" button when drawLines prop is false', function () {
        var props = __assign(__assign({}, defaultProps), { drawLines: false });
        setUp({ props: props });
        expect(screen.queryByTestId('branch-decorator')).not.toBeInTheDocument();
    });
    it('should render branch decorator for children', function () {
        var Child = function () { return React.createElement("span", null, "children"); };
        var props = __assign(__assign({}, defaultProps), { drawLines: true, children: React.createElement(Child, null) });
        setUp({ props: props });
        var decorators = screen.getAllByTestId('branch-decorator');
        within(decorators[0]).getByText('children');
        within(decorators[1]).getByText('More attributes');
    });
    it('should pin attributes correctly', function () {
        var pinnedAttributes = ['configuration/relationTypes/knowledge/attributes/Required'];
        var attrTypes = adjust(3, assoc('required', false), attributesList);
        var props = __assign(__assign({}, defaultProps), { attrTypes: attrTypes });
        setUp({ props: props, pinnedAttributesContextValue: pinnedAttributes });
        screen.getByText('Required');
    });
});
