/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import $ from "jquery";
import { ParamType } from "./types";
import { is_special_numeric } from "./infertypes";
;
export var FilterType;
(function (FilterType) {
    FilterType["All"] = "All";
    FilterType["Range"] = "Range";
    FilterType["Not"] = "Not";
    FilterType["Search"] = "Search";
})(FilterType || (FilterType = {}));
const FILTERS = {
    [FilterType.All]: filter_all,
    [FilterType.Range]: filter_range,
    [FilterType.Not]: filter_not,
    [FilterType.Search]: filter_search,
};
;
function filter_range(data) {
    if (data.type == ParamType.CATEGORICAL) {
        return function (dp) {
            const value = `${dp[data.col]}`;
            return value !== undefined && data.min <= value && value <= data.max;
        };
    }
    return function (dp) {
        const value = parseFloat(dp[data.col]);
        return value !== undefined && ((data.min <= value && value <= data.max) || (data.include_infnans && is_special_numeric(value)));
    };
}
;
function filter_search(data) {
    // Copied from Datatables to losely match search
    const escapeRegexp = $.fn.dataTable.util.escapeRegex;
    const pattern = escapeRegexp(data);
    const caseInsensitive = true;
    const regexp = new RegExp(pattern, caseInsensitive ? 'i' : '');
    return function (dp) {
        const sFilterRow = Object.values(dp).join('  ');
        return regexp.test(sFilterRow);
    };
}
function filter_all(data) {
    const f = data.map(function (f) { return FILTERS[f.type](f.data); });
    return function (dp) {
        return f.every((fn) => fn(dp));
    };
}
;
function filter_not(data) {
    const f = FILTERS[data.type];
    console.assert(f !== undefined, "Invalid filter", data);
    const fn = f(data.data);
    return dp => !fn(dp);
}
;
export function apply_filter(rows, filter) {
    const f = FILTERS[filter.type];
    console.assert(f !== undefined, "Invalid filter", filter);
    rows = rows.filter(f(filter.data));
    return rows;
}
export function apply_filters(rows, filters) {
    filters.forEach(function (filter) {
        rows = apply_filter(rows, filter);
    });
    return rows;
}
