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 { Mode, typeAheadSearch } from '@reltio/mdm-sdk';
import { EntitySelector } from './EntitySelector';
import { MdmModuleProvider } from '../contexts/MdmModuleContext';
import { getMuiIconByName } from '../test-utils';
jest.mock('@reltio/mdm-sdk', function () { return (__assign(__assign({}, jest.requireActual('@reltio/mdm-sdk')), { typeAheadSearch: jest.fn() })); });
var allEntities = [
    {
        uri: 'entities/uri1',
        label: 'Earth',
        secondaryLabel: 'Our planet',
        type: 'configuration/entityTypes/HCP'
    },
    {
        uri: 'entities/uri2',
        label: '',
        type: 'configuration/entityTypes/HCP'
    },
    {
        uri: 'entities/uri3',
        label: 'Phone',
        secondaryLabel: 'Device for calls',
        type: 'configuration/entityTypes/Company'
    },
    {
        uri: 'entities/uri4',
        label: 'Book',
        type: 'configuration/entityTypes/Company'
    }
];
var defaultMetadata = {
    entityTypes: [
        {
            uri: 'configuration/entityTypes/HCP',
            label: 'HCP',
            attributes: [
                {
                    uri: 'configuration/entityTypes/HCP/attributes/FirstName',
                    type: 'String',
                    name: 'FirstName',
                    label: 'First Name'
                },
                {
                    uri: 'configuration/entityTypes/HCP/attributes/LastName',
                    type: 'String',
                    name: 'LastName',
                    label: 'Last Name'
                }
            ]
        },
        { uri: 'configuration/entityTypes/Company', label: 'Company', attributes: [] },
        { uri: 'configuration/entityTypes/HCO', label: 'HCO', abstract: true }
    ]
};
var defaultGlobalSearchRequestOptions = {
    searchOptions: 'searchByOv',
    activityFilter: undefined,
    globalFilter: '123'
};
var defaultProps = {
    metadata: defaultMetadata,
    globalSearchRequestOptions: defaultGlobalSearchRequestOptions,
    mode: Mode.Editing,
    onChange: jest.fn()
};
var defaultMdmValues = {
    modifiedEntities: {},
    dependentLookups: { structure: {}, editors: {}, initedTypeUris: [] },
    uiPath: 'https://reltio.com'
};
var defaultMdmActions = {
    addAttributes: jest.fn(),
    removeAttribute: jest.fn(),
    modifyAttribute: jest.fn(),
    openEntity: 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.mdmActions, mdmActions = _e === void 0 ? defaultMdmActions : _e;
    var user = userEvent.setup();
    var Providers = function (_a) {
        var children = _a.children;
        return (React.createElement(MdmModuleProvider, { values: mdmValues, actions: mdmActions }, children));
    };
    return __assign(__assign({}, render(React.createElement(EntitySelector, __assign({}, props)), { wrapper: Providers })), { user: user });
};
describe('Entity selector tests', function () {
    beforeEach(function () {
        typeAheadSearch.mockImplementation(function (entityTypes, searchValue) {
            if (searchValue === void 0) { searchValue = ''; }
            var filteredEntities = allEntities.filter(function (_a) {
                var type = _a.type, label = _a.label;
                return entityTypes.some(function (_a) {
                    var uri = _a.uri;
                    return type === uri;
                }) &&
                    label.toLowerCase().startsWith(searchValue.toLowerCase());
            });
            return Promise.resolve(filteredEntities);
        });
    });
    afterEach(function () {
        jest.clearAllMocks();
    });
    it('should render correctly for single entity type', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user, options;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { entityTypesUris: ['configuration/entityTypes/HCP'] });
                    user = setUp({ props: props }).user;
                    screen.getByText('Select HCP profile');
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    options = screen.getAllByRole('option');
                    expect(options).toHaveLength(2);
                    expect(options[0]).toHaveTextContent('HEarth, Our planet');
                    expect(options[1]).toHaveTextContent('H<No label>');
                    expect(screen.queryByText('HCP')).not.toBeInTheDocument();
                    expect(screen.queryByText('Create new HCP')).not.toBeInTheDocument();
                    expect(typeAheadSearch).toHaveBeenCalledWith([defaultMetadata.entityTypes[0]], '', __assign(__assign({}, defaultGlobalSearchRequestOptions), { max: 20, sendMasked: false }));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render correctly for several entity types', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user, options;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { entityTypesUris: ['configuration/entityTypes/HCP', 'configuration/entityTypes/Company'] });
                    user = setUp({ props: props }).user;
                    screen.getByText('Select profile');
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    options = screen.getAllByRole('option');
                    expect(options).toHaveLength(4);
                    screen.getByText('HCP');
                    expect(options[0]).toHaveTextContent('HEarth, Our planet');
                    expect(options[1]).toHaveTextContent('H<No label>');
                    screen.getByText('Company');
                    expect(options[2]).toHaveTextContent('CPhone, Device for calls');
                    expect(options[3]).toHaveTextContent('CBook');
                    expect(screen.queryByText('Create new HCP')).not.toBeInTheDocument();
                    expect(screen.queryByText('Create new Company')).not.toBeInTheDocument();
                    expect(typeAheadSearch).toHaveBeenCalledWith([defaultMetadata.entityTypes[0], defaultMetadata.entityTypes[1]], '', __assign(__assign({}, defaultGlobalSearchRequestOptions), { max: 20, sendMasked: false }));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render correctly for several entity types in case of entities list has only one type', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user, options;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    typeAheadSearch.mockResolvedValue(allEntities.slice(0, 2));
                    props = __assign(__assign({}, defaultProps), { entityTypesUris: ['configuration/entityTypes/HCP', 'configuration/entityTypes/Company'] });
                    user = setUp({ props: props }).user;
                    screen.getByText('Select profile');
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    options = screen.getAllByRole('option');
                    expect(options).toHaveLength(2);
                    expect(options[0]).toHaveTextContent('HEarth, Our planet');
                    expect(options[1]).toHaveTextContent('H<No label>');
                    expect(screen.queryByText('HCP')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render correctly in case of no results found', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    typeAheadSearch.mockResolvedValue([]);
                    props = __assign(__assign({}, defaultProps), { entityTypesUris: ['configuration/entityTypes/HCP'] });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    screen.getByText('No results found');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should search correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user, options;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { max: 10, entityTypesUris: ['configuration/entityTypes/HCP'] });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.type(screen.getByRole('combobox'), 'ea')];
                case 1:
                    _a.sent();
                    options = screen.getAllByRole('option');
                    expect(options).toHaveLength(1);
                    expect(options[0]).toHaveTextContent('HEarth, Our planet');
                    expect(typeAheadSearch).toHaveBeenCalledWith([defaultMetadata.entityTypes[0]], 'ea', __assign(__assign({}, defaultGlobalSearchRequestOptions), { max: 10, sendMasked: false }));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not send typeAheadSearch request if have not available entity type', 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), { max: 10, entityTypesUris: ['configuration/entityTypes/HCP'], metadata: {
                            entityTypes: [{ uri: 'configuration/entityTypes/HCP', label: 'HCP', attributes: [], access: [] }]
                        } });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByRole('combobox'))];
                case 1:
                    _a.sent();
                    expect(typeAheadSearch).not.toHaveBeenCalled();
                    screen.getByText('No results found');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render correctly in case of temp entity', function () { return __awaiter(void 0, void 0, void 0, function () {
        var entityUri, entityType, mdmValues, props, user, entityCreator;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    entityUri = 'entities/uri$$123';
                    entityType = 'configuration/entityTypes/HCP';
                    mdmValues = __assign(__assign({}, defaultMdmValues), { modifiedEntities: (_a = {}, _a[entityUri] = { uri: entityUri, type: entityType }, _a) });
                    props = __assign(__assign({}, defaultProps), { mode: Mode.Editing, entityTypesUris: [entityType], entity: { entityUri: entityUri, entityType: entityType, entityLabel: 'Temp entity' } });
                    user = setUp({ props: props, mdmValues: mdmValues }).user;
                    expect(screen.getByText('New HCP will be created')).not.toHaveAttribute('href');
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _b.sent();
                    entityCreator = screen.getByTestId('entity-creator');
                    within(entityCreator).getByText('First Name');
                    within(entityCreator).getByText('Last Name');
                    expect(getMuiIconByName('Clear')).toBeInTheDocument();
                    return [4 /*yield*/, user.click(getMuiIconByName('Clear'))];
                case 2:
                    _b.sent();
                    expect(props.onChange).toHaveBeenCalledWith({});
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render correctly in case of existing entity', function () { return __awaiter(void 0, void 0, void 0, function () {
        var entity, props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    entity = allEntities[0];
                    props = __assign(__assign({}, defaultProps), { mode: Mode.Editing, entityTypesUris: [entity.type], entity: { entityUri: entity.uri, entityType: entity.type, entityLabel: entity.label } });
                    user = setUp({ props: props }).user;
                    expect(screen.getByRole('link', { name: 'Earth' })).toHaveAttribute('href', 'https://reltio.com#p~com.reltio.plugins.entity.default.DefaultPerspective_e~entities/uri1');
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    expect(screen.queryByTestId('entity-creator')).not.toBeInTheDocument();
                    expect(getMuiIconByName('Clear')).not.toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should not open entity by click on link if "disableLinkClick" select prop is true', function () { return __awaiter(void 0, void 0, void 0, function () {
        var entity, props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    entity = allEntities[0];
                    props = __assign(__assign({}, defaultProps), { disableLinkClick: true, mode: Mode.Editing, entityTypesUris: [entity.type], entity: { entityUri: entity.uri, entityType: entity.type, entityLabel: entity.label } });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByText('Earth'))];
                case 1:
                    _a.sent();
                    expect(defaultMdmActions.openEntity).not.toHaveBeenCalled();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should use default behaviour for link if control or command is pressed', function () { return __awaiter(void 0, void 0, void 0, function () {
        var entity, props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    entity = allEntities[0];
                    props = __assign(__assign({}, defaultProps), { mode: Mode.Editing, entityTypesUris: [entity.type], entity: { entityUri: entity.uri, entityType: entity.type, entityLabel: entity.label } });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.keyboard('{Control>}')];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('Earth'))];
                case 2:
                    _a.sent();
                    expect(defaultMdmActions.openEntity).not.toHaveBeenCalled();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should open entity by click on click in basic case correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var entity, props, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    entity = allEntities[0];
                    props = __assign(__assign({}, defaultProps), { mode: Mode.Editing, entityTypesUris: [entity.type], entity: { entityUri: entity.uri, entityType: entity.type, entityLabel: entity.label } });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByText('Earth'))];
                case 1:
                    _a.sent();
                    expect(defaultMdmActions.openEntity).toHaveBeenCalledWith({ uri: 'entities/uri1' });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should change entity correctly', 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), { entityTypesUris: ['configuration/entityTypes/HCP'] });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('Earth'))];
                case 2:
                    _a.sent();
                    expect(props.onChange).toHaveBeenCalledWith(__assign({ entityType: defaultMetadata.entityTypes[0] }, allEntities[0]));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call typeAheadSearch with new entity types when entityTypesUris prop changes after rerender', function () { return __awaiter(void 0, void 0, void 0, function () {
        var initialProps, _a, user, rerender, updatedProps;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    initialProps = __assign(__assign({}, defaultProps), { entityTypesUris: ['configuration/entityTypes/HCP'] });
                    _a = setUp({ props: initialProps }), user = _a.user, rerender = _a.rerender;
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _b.sent();
                    expect(typeAheadSearch).toHaveBeenCalledWith([defaultMetadata.entityTypes[0]], '', expect.any(Object));
                    typeAheadSearch.mockClear();
                    updatedProps = __assign(__assign({}, defaultProps), { entityTypesUris: ['configuration/entityTypes/HCP', 'configuration/entityTypes/Company'] });
                    rerender(React.createElement(MdmModuleProvider, { values: defaultMdmValues, actions: defaultMdmActions },
                        React.createElement(EntitySelector, __assign({}, updatedProps))));
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 2:
                    _b.sent();
                    expect(typeAheadSearch).toHaveBeenCalledWith([defaultMetadata.entityTypes[0], defaultMetadata.entityTypes[1]], '', expect.any(Object));
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render create button and handle click correctly for single entity type in case of onCreate prop is passed and input is filled', 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), { onCreate: jest.fn(), entityTypesUris: ['configuration/entityTypes/HCP'] });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.type(screen.getByRole('combobox'), 'ea')];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(screen.getByText('Create "ea" as new HCP'))];
                case 2:
                    _a.sent();
                    expect(props.onCreate).toHaveBeenCalledWith('configuration/entityTypes/HCP', 'ea');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render create button and handle click correctly for single entity type in case of onCreate prop is passed and input is empty', 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), { onCreate: jest.fn(), entityTypesUris: ['configuration/entityTypes/HCP'] });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    screen.getByText('Create new HCP');
                    return [4 /*yield*/, user.click(screen.getByText('Create new HCP'))];
                case 2:
                    _a.sent();
                    expect(props.onCreate).toHaveBeenCalledWith('configuration/entityTypes/HCP', '');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render create buttons and handle click correctly for several entity types in case of onCreate prop is passed and input is filled', function () { return __awaiter(void 0, void 0, void 0, function () {
        var props, user, input;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    props = __assign(__assign({}, defaultProps), { onCreate: jest.fn(), entityTypesUris: ['configuration/entityTypes/HCP', 'configuration/entityTypes/Company'] });
                    user = setUp({ props: props }).user;
                    input = screen.getByRole('combobox');
                    return [4 /*yield*/, user.type(input, 'bo')];
                case 1:
                    _a.sent();
                    expect(input).toHaveValue('bo');
                    screen.getByText('Create "bo" as new HCP');
                    return [4 /*yield*/, user.click(screen.getByText('Create "bo" as new Company'))];
                case 2:
                    _a.sent();
                    expect(props.onCreate).toHaveBeenCalledWith('configuration/entityTypes/Company', 'bo');
                    expect(input).toHaveValue('');
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render create buttons and handle click correctly for several entity types in case of onCreate prop is passed and input is empty', 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), { onCreate: jest.fn(), entityTypesUris: ['configuration/entityTypes/HCP', 'configuration/entityTypes/Company'] });
                    user = setUp({ props: props }).user;
                    return [4 /*yield*/, user.click(screen.getByTestId('select-dropdown-indicator'))];
                case 1:
                    _a.sent();
                    screen.getByText('Create new HCP');
                    return [4 /*yield*/, user.click(screen.getByText('Create new Company'))];
                case 2:
                    _a.sent();
                    expect(props.onCreate).toHaveBeenCalledWith('configuration/entityTypes/Company', '');
                    return [2 /*return*/];
            }
        });
    }); });
});
