var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { Dropdown } from "semantic-ui-react";
import * as React from 'react';
import { useState, useEffect } from "react";
export function createDropdownMulti(config) {
    var mapResult = function (item, id) { return ({
        value: id,
        key: "" + item[config.key],
        text: config.display(item)
    }); };
    var mapSelData = config.useOnlyKey
        ? function (i) { return i[config.key]; }
        : function (i) { return i; };
    var findIndex = config.useOnlyKey
        ? function (key) { return function (i) { return "" + i === key; }; }
        : function (key) { return function (i) { return "" + i[config.key] === key; }; };
    return function (props) {
        var onChange = props.onChange, value = props.value, onSetError = props.onSetError, ctlProps = __rest(props, ["onChange", "value", "onSetError"]);
        var _a = useState(false), loading = _a[0], setLoading = _a[1];
        var _b = useState([]), results = _b[0], setResults = _b[1];
        var _c = useState([]), data = _c[0], setData = _c[1];
        useEffect(function () {
            setLoading(true);
            config.getData('')
                .then(function (res) {
                setResults(res.map(mapResult));
                setData(res);
                setLoading(false);
            })
                .catch(function (err) {
                setResults([]);
                setLoading(false);
            });
        }, []);
        var getValues = function () {
            return value && results.map(function (res, ix) {
                return value.findIndex(findIndex(res.key));
            }).filter(function (i) { return i > -1; }) || [];
        };
        var handleOnChange = function (v) {
            onChange(v);
        };
        var handleResultSelect = function (event, d) {
            var ix = d.value;
            var selData = ix.map(function (i) { return data[i]; }).map(mapSelData);
            handleOnChange(selData);
        };
        return <Dropdown {...ctlProps} loading={loading} onChange={handleResultSelect} selection multiple search value={getValues()} options={results}/>;
    };
}
