"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 styles_1 = require("@mui/material/styles");
var styles_2 = require("@mui/styles");
var LocalizationProvider_1 = require("@mui/x-date-pickers/LocalizationProvider");
var AdapterMoment_1 = require("@mui/x-date-pickers/AdapterMoment");
var react_2 = require("@testing-library/react");
var user_event_1 = __importDefault(require("@testing-library/user-event"));
var attributes_test_data_1 = require("./attributes.test-data");
var metadata_test_data_1 = require("./metadata.test-data");
var AttributesFiltersBuilder_1 = require("../AttributesFiltersBuilder");
var TestStylesProvider_1 = require("../test-utils/TestStylesProvider");
var constants_1 = require("../constants");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
jest.unmock('@mui/styles');
describe('Attributes filters builder tests', function () {
    var onChangeSpy = jest.fn();
    var filters = [
        {
            fieldName: 'attributes.Int',
            filter: 'equals',
            values: [['99']]
        },
        {
            fieldName: 'attributes.NestedTest.NestedTestL2.DateL2',
            filter: 'on',
            values: [1683590400000]
        },
        { fieldName: undefined, filter: undefined, values: [] }
    ];
    afterEach(function () {
        jest.clearAllMocks();
    });
    var mdmValues = {
        metadata: metadata_test_data_1.metadata,
        tenant: {
            id: 't1',
            name: 't1'
        },
        lookups: {},
        globalSearchRequestOptions: {}
    };
    var setUp = function (props) {
        if (props === void 0) { props = {}; }
        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 },
                react_1.default.createElement(styles_2.ThemeProvider, { theme: (0, styles_1.createTheme)(constants_1.theme) },
                    react_1.default.createElement(TestStylesProvider_1.TestStylesProvider, null,
                        react_1.default.createElement(LocalizationProvider_1.LocalizationProvider, { dateAdapter: AdapterMoment_1.AdapterMoment }, children)))));
        };
        var defaultProps = { attributesTypesGroups: attributes_test_data_1.attributesTypesGroups, filters: filters, onChange: onChangeSpy };
        return __assign({ user: user }, (0, react_2.render)(react_1.default.createElement(AttributesFiltersBuilder_1.AttributesFiltersBuilder, __assign({}, defaultProps, props)), { wrapper: Providers }));
    };
    it('should render default state correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, actionButtons, attributeSelector;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({ filters: [] }).user;
                    expect(react_2.screen.getByText('Select attribute')).toBeInTheDocument();
                    expect(react_2.screen.getByText('Equals')).toBeInTheDocument();
                    expect(react_2.screen.getByRole('combobox')).toBeDisabled();
                    actionButtons = react_2.screen.getAllByTestId('query-builder-row-actions');
                    expect(actionButtons).toHaveLength(1);
                    expect((0, react_2.within)(actionButtons[0]).getByTestId('query-builder-row-actions-add')).toBeInTheDocument();
                    expect((0, react_2.within)(actionButtons[0]).queryByTestId('query-builder-row-actions-duplicate')).not.toBeInTheDocument();
                    expect((0, react_2.within)(actionButtons[0]).getByTestId('query-builder-row-actions-delete')).toBeInTheDocument();
                    attributeSelector = react_2.screen.getByTestId('attribute-selector');
                    return [4 /*yield*/, user.click((0, react_2.within)(attributeSelector).getByRole('button'))];
                case 1:
                    _a.sent();
                    expect(react_2.screen.getByRole('presentation')).toBeInTheDocument();
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render filters correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var rows, intRow, dateRow, emptyRow, newRow;
        return __generator(this, function (_a) {
            setUp();
            rows = react_2.screen.getAllByTestId('query-builder-row');
            intRow = rows[0], dateRow = rows[1], emptyRow = rows[2], newRow = rows[3];
            expect(rows).toHaveLength(4);
            expect((0, react_2.within)(intRow).getByTestId('attribute-selector')).toHaveTextContent('Int');
            expect((0, react_2.within)(intRow).getByText('Equals')).toBeInTheDocument();
            expect((0, react_2.within)(intRow).getByTestId('filter-value-editor')).toHaveTextContent('99');
            expect((0, react_2.within)(dateRow).getByTestId('attribute-selector')).toHaveTextContent('Nested Test / Nested Test Level 2 / Date Level 2');
            expect((0, react_2.within)(dateRow).getByText('On')).toBeInTheDocument();
            expect((0, react_2.within)(dateRow).getByRole('textbox')).toHaveValue('05/09/2023');
            expect((0, react_2.within)(emptyRow).getByTestId('attribute-selector')).toHaveTextContent('Select attribute');
            expect((0, react_2.within)(emptyRow).getByText('Equals')).toBeInTheDocument();
            expect((0, react_2.within)(emptyRow).queryByTestId('filter-value-editor')).not.toBeInTheDocument();
            expect((0, react_2.within)(newRow).getByTestId('attribute-selector')).toHaveTextContent('Select attribute');
            expect((0, react_2.within)(newRow).getByText('Equals')).toBeInTheDocument();
            expect((0, react_2.within)(newRow).queryByTestId('filter-value-editor')).not.toBeInTheDocument();
            return [2 /*return*/];
        });
    }); });
    it('should render attribute groups correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var expectedAttributes, user, attributeSelector, items;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    expectedAttributes = [
                        'Country Code',
                        'Int',
                        'Image Gallery',
                        'Full image url (S3)',
                        'Float',
                        'Nested Test',
                        'String',
                        'Nested Test Level 2',
                        'Date Level 2',
                        'HCP to HCA Affiliations',
                        'Affiliated Type'
                    ];
                    user = setUp({ filters: [] }).user;
                    attributeSelector = react_2.screen.getByTestId('attribute-selector');
                    return [4 /*yield*/, user.click((0, react_2.within)(attributeSelector).getByRole('button'))];
                case 1:
                    _a.sent();
                    items = react_2.screen.getAllByRole('menuitem');
                    items.forEach(function (item, index) {
                        expect(item).toHaveTextContent(expectedAttributes[index]);
                    });
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange prop after filter changes', function () { return __awaiter(void 0, void 0, void 0, function () {
        var filters, user, rows, selector;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    filters = [{ fieldName: 'attributes.Int', filter: 'equals', values: [['1']] }];
                    user = setUp({ filters: filters }).user;
                    rows = react_2.screen.getAllByTestId('query-builder-row');
                    selector = (0, react_2.within)(rows[0]).getByTestId('filter-selector');
                    return [4 /*yield*/, user.click(selector)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('option', { name: 'Not' }))];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([{ fieldName: 'attributes.Int', filter: 'not equals', values: [] }]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange prop after value changes', function () { return __awaiter(void 0, void 0, void 0, function () {
        var filters, user, rows, editor, input;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    filters = [{ fieldName: 'attributes.Int', filter: 'equals', values: [['1']] }];
                    user = setUp({ filters: filters }).user;
                    rows = react_2.screen.getAllByTestId('query-builder-row');
                    editor = (0, react_2.within)(rows[0]).getByTestId('filter-value-editor');
                    input = (0, react_2.within)(editor).getByRole('textbox');
                    return [4 /*yield*/, user.type(input, '12')];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.keyboard('{Enter}')];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([
                        { fieldName: 'attributes.Int', filter: 'equals', values: [['1', '12']] }
                    ]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange with correct fieldName for simple attributes', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, attributeSelector;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({ filters: [] }).user;
                    attributeSelector = react_2.screen.getByTestId('attribute-selector');
                    return [4 /*yield*/, user.click((0, react_2.within)(attributeSelector).getByRole('button'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('menuitem', { name: 'Int' }))];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([
                        { fieldName: 'attributes.Int', filter: null, operator: 'and', values: [] }
                    ]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange with correct fieldName for existing simple attribute', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, attributeSelectors;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({
                        filters: [{ fieldName: 'attributes.Int', filter: 'equals', values: [['99']], operator: 'or' }]
                    }).user;
                    attributeSelectors = react_2.screen.getAllByTestId('attribute-selector');
                    return [4 /*yield*/, user.click((0, react_2.within)(attributeSelectors[0]).getByRole('button'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('menuitem', { name: 'Country Code' }))];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([
                        { fieldName: 'attributes.CountryCode', filter: 'equals', operator: 'or', values: [] }
                    ]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange with correct fieldName for nested attributes', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, attributeSelector;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({ filters: [] }).user;
                    attributeSelector = react_2.screen.getByTestId('attribute-selector');
                    return [4 /*yield*/, user.click((0, react_2.within)(attributeSelector).getByRole('button'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('menuitem', { name: 'Date Level 2' }))];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([
                        { fieldName: 'attributes.NestedTest.NestedTestL2.DateL2', filter: null, operator: 'and', values: [] }
                    ]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange with correct fieldName for reference attributes', function () { return __awaiter(void 0, void 0, void 0, function () {
        var user, attributeSelector;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = setUp({ filters: [] }).user;
                    attributeSelector = react_2.screen.getByTestId('attribute-selector');
                    return [4 /*yield*/, user.click((0, react_2.within)(attributeSelector).getByRole('button'))];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('menuitem', { name: 'Affiliated Type' }))];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([
                        { fieldName: 'attributes.Affiliations.AffiliatedType', filter: null, operator: 'and', values: [] }
                    ]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange prop after add filter', function () { return __awaiter(void 0, void 0, void 0, function () {
        var newFilter, user, attributeSelectors, lastSelector, selectorButton;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    newFilter = { fieldName: 'attributes.CountryCode', filter: null, values: [], operator: 'and' };
                    user = setUp().user;
                    attributeSelectors = react_2.screen.getAllByTestId('attribute-selector');
                    lastSelector = attributeSelectors[attributeSelectors.length - 1];
                    selectorButton = (0, react_2.within)(lastSelector).getByRole('button');
                    return [4 /*yield*/, user.click(selectorButton)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, user.click(react_2.screen.getByRole('menuitem', { name: 'Country Code' }))];
                case 2:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([filters[0], filters[1], filters[2], newFilter]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should render row actions correctly', function () { return __awaiter(void 0, void 0, void 0, function () {
        var rows;
        return __generator(this, function (_a) {
            setUp();
            rows = react_2.screen.getAllByTestId('query-builder-row');
            expect(rows).toHaveLength(4);
            (0, react_2.within)(rows[0]).getByLabelText('Add');
            (0, react_2.within)(rows[0]).getByLabelText('Duplicate');
            (0, react_2.within)(rows[0]).getByLabelText('Delete');
            expect((0, react_2.within)(rows[0]).getByTestId('query-builder-row-actions')).not.toHaveClass('hidden');
            (0, react_2.within)(rows[1]).getByLabelText('Add');
            (0, react_2.within)(rows[1]).getByLabelText('Duplicate');
            (0, react_2.within)(rows[1]).getByLabelText('Delete');
            expect((0, react_2.within)(rows[1]).getByTestId('query-builder-row-actions')).not.toHaveClass('hidden');
            (0, react_2.within)(rows[2]).getByLabelText('Add');
            (0, react_2.within)(rows[2]).getByLabelText('Delete');
            expect((0, react_2.within)(rows[2]).queryByLabelText('Duplicate')).not.toBeInTheDocument();
            expect((0, react_2.within)(rows[2]).getByTestId('query-builder-row-actions')).not.toHaveClass('hidden');
            expect((0, react_2.within)(rows[3]).getByTestId('query-builder-row-actions')).toHaveClass('hidden');
            return [2 /*return*/];
        });
    }); });
    it('should call onChange prop after add new row', function () { return __awaiter(void 0, void 0, void 0, function () {
        var emptyFilter, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    emptyFilter = { fieldName: null, filter: null, values: [], operator: 'and' };
                    user = setUp().user;
                    return [4 /*yield*/, user.click(react_2.screen.getAllByRole('button', { name: 'Add' })[0])];
                case 1:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([filters[0], emptyFilter, filters[1], filters[2]]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange prop after remove row', 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.getAllByRole('button', { name: 'Delete' })[1])];
                case 1:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([filters[0], filters[2]]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should call onChange prop after duplicate row', 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.getAllByRole('button', { name: 'Duplicate' })[1])];
                case 1:
                    _a.sent();
                    expect(onChangeSpy).toHaveBeenCalledWith([filters[0], filters[1], filters[1], filters[2]]);
                    return [2 /*return*/];
            }
        });
    }); });
    it('should pass custom editor components from props', function () {
        var CustomValuesEditor = function () { return react_1.default.createElement("div", { "data-reltio-id": "custom-values-editor" }); };
        var CustomFilterSelector = function () { return react_1.default.createElement("div", { "data-reltio-id": "custom-filter-selector" }); };
        var props = {
            filters: [{ fieldName: 'attributes.Int', filter: 'equals', values: [['12345']] }],
            components: { ValuesEditor: CustomValuesEditor, FilterSelector: CustomFilterSelector }
        };
        setUp(props);
        var editors = react_2.screen.getAllByTestId('custom-values-editor');
        var selectors = react_2.screen.getAllByTestId('custom-filter-selector');
        expect(editors).toHaveLength(2);
        expect(selectors).toHaveLength(2);
    });
});
