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 createDropdown(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; };
    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 getValue = function () {
            if (config.useOnlyKey) {
                return value && results.findIndex(function (r) { return "" + r.key === "" + value; });
            }
            else {
                return value && results.findIndex(function (r) { return "" + r.key === "" + value[config.key]; });
            }
        };
        var handleOnChange = function (v) {
            onChange(v);
        };
        var handleResultSelect = function (event, d) {
            if (d.value !== undefined) {
                var item = mapSelData(data[d.value]);
                handleOnChange(item);
            }
            else {
                handleOnChange(undefined);
            }
        };
        return <Dropdown {...ctlProps} loading={loading} onChange={handleResultSelect} selection value={getValue()} options={results}/>;
    };
}
