"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColumnFilter = void 0;
var react_1 = __importStar(require("react"));
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var Popover_1 = __importDefault(require("@mui/material/Popover"));
var IconButton_1 = __importDefault(require("@mui/material/IconButton"));
var ArrowDropDown_1 = __importDefault(require("@mui/icons-material/ArrowDropDown"));
var FilterChip_1 = require("../FilterChip");
var FilterEditor_1 = require("../../../../FilterEditor");
var basicTable_1 = require("../../../../helpers/basicTable");
var helpers_1 = require("./helpers");
var styles_1 = require("../../styles");
var ColumnFilter = function (_a) {
    var _b;
    var columnId = _a.columnId, dataTypeDefinition = _a.dataTypeDefinition, filter = _a.filter, filterOptionsData = _a.filterOptionsData, onFilter = _a.onFilter;
    var styles = (0, styles_1.useStyles)();
    var _c = (0, react_1.useState)(null), anchorEl = _c[0], setAnchorEl = _c[1];
    var openFilterPopup = function (event) { return setAnchorEl(event.currentTarget); };
    var closeFilterPopup = function () { return setAnchorEl(null); };
    var _d = (0, react_1.useState)(filter), columnFilter = _d[0], setColumnFilter = _d[1];
    (0, react_1.useEffect)(function () {
        setColumnFilter(filter);
    }, [filter]);
    var containerRef = (0, react_1.useRef)(null);
    var mdmFilter = (0, basicTable_1.columnFilterToMdmFilter)({ id: columnId, dataTypeDefinition: dataTypeDefinition }, columnFilter);
    var applyFilterChange = function (newFilter) {
        if (newFilter !== filter) {
            onFilter({ columnId: columnId, filter: newFilter });
        }
    };
    var clearFilter = function () { return applyFilterChange(); };
    var applyChangesAndClose = function () {
        var isValidFilter = (0, mdm_sdk_1.validateFilter)(mdmFilter);
        if (isValidFilter) {
            applyFilterChange(columnFilter);
        }
        else {
            clearFilter();
        }
        closeFilterPopup();
    };
    var handleValueEditorKeyPress = function (event) {
        if (event.key !== 'Enter')
            return;
        event.stopPropagation();
        event.preventDefault();
        applyChangesAndClose();
    };
    var getFilterOptionData = function (filterOption) {
        return filterOptionsData && filterOptionsData.find((0, ramda_1.propEq)('value', filterOption));
    };
    var getFilterLabel = function (filterOption) {
        return (0, ramda_1.pipe)(getFilterOptionData, (0, ramda_1.prop)('label'), (0, ramda_1.defaultTo)((0, mdm_sdk_1.getFilterOptionLabel)(filterOption)))(filterOption);
    };
    var getFilterDataTypeDefinition = function (filterOption) {
        return (0, ramda_1.pipe)(getFilterOptionData, (0, ramda_1.prop)('dataTypeDefinition'), (0, ramda_1.defaultTo)((0, mdm_sdk_1.getDataTypeDefinitionForFilterValue)(dataTypeDefinition, filterOption)))(filterOption);
    };
    var filterOptionValues = (_b = filterOptionsData === null || filterOptionsData === void 0 ? void 0 : filterOptionsData.map(function (filterOption) { return filterOption.value; })) !== null && _b !== void 0 ? _b : (0, mdm_sdk_1.getFilterOptionsForDataTypeDefinition)(dataTypeDefinition);
    var filterOptions = filterOptionValues.map(function (value) { return ({ value: value, label: getFilterLabel(value) }); });
    var hasReadPermission = (0, mdm_sdk_1.checkBasicMetadataPermission)(mdm_sdk_1.MetadataPermissions.READ, dataTypeDefinition);
    return (react_1.default.createElement("div", { ref: containerRef, className: styles.columnFilter, "data-reltio-id": "column-filter" },
        filter && (react_1.default.createElement(FilterChip_1.FilterChip, { filterValue: filter.value, filterOption: filterOptions.find((0, ramda_1.propEq)('value', filter.filter)), onDelete: clearFilter, dataTypeDefinition: getFilterDataTypeDefinition(filter.filter) })),
        hasReadPermission && (react_1.default.createElement(IconButton_1.default, { className: styles.dropDownButton, onClick: openFilterPopup, disableFocusRipple: true, size: "large" },
            react_1.default.createElement(ArrowDropDown_1.default, null))),
        react_1.default.createElement(Popover_1.default, { PaperProps: {
                style: {
                    width: "".concat(containerRef.current ? containerRef.current.getBoundingClientRect().width : 0, "px")
                }
            }, open: !!anchorEl, anchorEl: anchorEl, anchorOrigin: {
                vertical: 'bottom',
                horizontal: 'right'
            }, transformOrigin: {
                vertical: 'top',
                horizontal: 'right'
            }, classes: { paper: styles.filterMenu }, onClose: applyChangesAndClose },
            react_1.default.createElement(FilterEditor_1.FilterEditor, { classes: { option: styles['filter-editor__option'] }, value: mdmFilter, onChange: (0, ramda_1.pipe)(helpers_1.mdmFilterToColumnFilter, setColumnFilter), filterOptions: filterOptions, dataTypeDefinition: getFilterDataTypeDefinition(mdmFilter.filter), ValueEditorProps: {
                    TextFieldProps: {
                        onKeyPress: handleValueEditorKeyPress
                    },
                    fullWidth: true
                } }))));
};
exports.ColumnFilter = ColumnFilter;
