define(["require", "exports", "tslib", "react", "@uifabric/experiments/lib/UnifiedPeoplePicker", "@uifabric/example-data", "@uifabric/experiments/lib/SelectedItemsList", "@uifabric/experiments/lib/FloatingSuggestions", "@uifabric/experiments/lib/FloatingPeopleSuggestions"], function (require, exports, tslib_1, React, UnifiedPeoplePicker_1, example_data_1, SelectedItemsList_1, FloatingSuggestions_1, FloatingPeopleSuggestions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var _suggestions = [
        {
            key: '1',
            id: '1',
            displayText: 'Suggestion 1',
            item: example_data_1.mru[0],
            isSelected: true,
            showRemoveButton: true,
        },
        {
            key: '2',
            id: '2',
            displayText: 'Suggestion 2',
            item: example_data_1.mru[1],
            isSelected: false,
            showRemoveButton: true,
        },
        {
            key: '3',
            id: '3',
            displayText: 'Suggestion 3',
            item: example_data_1.mru[2],
            isSelected: false,
            showRemoveButton: true,
        },
        {
            key: '4',
            id: '4',
            displayText: 'Suggestion 4',
            item: example_data_1.mru[3],
            isSelected: false,
            showRemoveButton: true,
        },
        {
            key: '5',
            id: '5',
            displayText: 'Suggestion 5',
            item: example_data_1.mru[4],
            isSelected: false,
            showRemoveButton: true,
        },
    ];
    exports.UnifiedPeoplePickerWithEditExample = function () {
        var _a = React.useState(tslib_1.__spreadArrays(_suggestions)), peopleSuggestions = _a[0], setPeopleSuggestions = _a[1];
        var _b = React.useState([]), peopleSelectedItems = _b[0], setPeopleSelectedItems = _b[1];
        var ref = React.useRef();
        // Used to resolve suggestions on the editableItem
        var model = new ExampleSuggestionsModel(example_data_1.people);
        var suggestionsStore = new FloatingSuggestions_1.SuggestionsStore();
        /**
         * Build a custom selected item capable of being edited when the item is right clicked
         */
        var SelectedItem = SelectedItemsList_1.EditableItem({
            itemComponent: SelectedItemsList_1.TriggerOnContextMenu(SelectedItemsList_1.SelectedPersona),
            editingItemComponent: SelectedItemsList_1.DefaultEditingItem({
                getEditingItemText: function (persona) { return persona.text || ''; },
                onRenderFloatingPicker: function (props) { return (React.createElement(FloatingPeopleSuggestions_1.FloatingPeopleSuggestions, tslib_1.__assign({}, props, { suggestionsStore: suggestionsStore, onResolveSuggestions: model.resolveSuggestions }))); },
            }),
        });
        var _onSuggestionSelected = function (ev, item) {
            _markSuggestionSelected(item);
            setPeopleSelectedItems(function (prevPeopleSelectedItems) { return tslib_1.__spreadArrays(prevPeopleSelectedItems, [item.item]); });
        };
        var _onSuggestionRemoved = function (ev, suggestionToRemove) {
            // Intentionally checking on complete item object to ensure it is removed. Id cannot be used as the
            // property is not populated for all the suggestions, and key does not exist on type checking.
            setPeopleSuggestions(function (suggestions) {
                var modifiedSuggestions = suggestions.filter(function (suggestion) { return suggestion.item !== suggestionToRemove.item; });
                return modifiedSuggestions;
            });
        };
        var _markSuggestionSelected = function (selectedSuggestion) {
            setPeopleSuggestions(function (suggestions) {
                var modifiedSuggestions = suggestions.map(function (suggestion) {
                    return suggestion.id === selectedSuggestion.id
                        ? tslib_1.__assign(tslib_1.__assign({}, suggestion), { isSelected: true }) : tslib_1.__assign(tslib_1.__assign({}, suggestion), { isSelected: false });
                });
                return modifiedSuggestions;
            });
        };
        var _getItemsCopyText = function (itemsToCopy) {
            var copyText = '';
            if (itemsToCopy && itemsToCopy.length > 0) {
                itemsToCopy.forEach(function (item) {
                    copyText = copyText.concat((item.text || '') + ',');
                });
            }
            return copyText;
        };
        var _onPaste = function (pastedValue, selectedItemsList) {
            // Find the suggestion corresponding to the specific text name
            // and update the selectedItemsList to re-render everything.
            var newList = [];
            if (pastedValue !== null) {
                pastedValue.split(',').forEach(function (textValue) {
                    if (textValue) {
                        example_data_1.people.forEach(function (suggestionItem) {
                            if (suggestionItem.text === textValue) {
                                selectedItemsList.push(suggestionItem);
                                newList.push(suggestionItem);
                            }
                        });
                    }
                });
            }
            setPeopleSelectedItems(function (prevPeopleSelectedItems) { return tslib_1.__spreadArrays(prevPeopleSelectedItems, newList); });
        };
        var _dropItemsAt = function (insertIndex, newItems, indicesToRemove) {
            // Insert those items into the current list
            if (insertIndex > -1) {
                var currentItems = tslib_1.__spreadArrays(peopleSelectedItems);
                var updatedItems_1 = [];
                for (var i = 0; i < currentItems.length; i++) {
                    var item = currentItems[i];
                    // If this is the insert before index, insert the dragged items, then the current item
                    if (i === insertIndex) {
                        newItems.forEach(function (draggedItem) {
                            updatedItems_1.push(draggedItem);
                        });
                        updatedItems_1.push(item);
                    }
                    else if (!indicesToRemove.includes(i)) {
                        // only insert items into the new list that are not being dragged
                        updatedItems_1.push(item);
                    }
                }
                setPeopleSelectedItems(updatedItems_1);
            }
        };
        var _onItemsRemoved = function (itemsToRemove) {
            // Updating the local copy as well at the parent level.
            var currentItems = tslib_1.__spreadArrays(peopleSelectedItems);
            var updatedItems = currentItems;
            // Intentionally not using .filter here as we want to only remove a specific
            // item in case of duplicates of same item.
            itemsToRemove.forEach(function (item) {
                var index = updatedItems.indexOf(item);
                updatedItems.splice(index, 1);
            });
            setPeopleSelectedItems(updatedItems);
        };
        var _replaceItem = function (newItem, index) {
            var newItemsArray = !Array.isArray(newItem) ? [newItem] : newItem;
            if (index >= 0) {
                var newItems = tslib_1.__spreadArrays(peopleSelectedItems);
                newItems.splice.apply(newItems, tslib_1.__spreadArrays([index, 1], newItemsArray));
                setPeopleSelectedItems(newItems);
            }
        };
        var _onInputChange = function (filterText) {
            var _a;
            // Clear the input if the user types a semicolon or comma
            // This is meant to be an example of using the forward ref,
            // feel free to comment out if it impacts your testing
            var lastCharIndex = filterText.length - 1;
            var lastChar = filterText[lastCharIndex];
            if (lastChar === ';' || lastChar === ',') {
                (_a = ref.current) === null || _a === void 0 ? void 0 : _a.clearInput();
            }
            var allPeople = example_data_1.people;
            var suggestions = allPeople.filter(function (item) { return _startsWith(item.text || '', filterText); });
            var suggestionList = suggestions.map(function (item) {
                return { item: item, isSelected: false, key: item.key };
            });
            // We want to show top 5 results
            setPeopleSuggestions(suggestionList.splice(0, 5));
        };
        function _startsWith(text, filterText) {
            return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
        }
        var floatingPeoplePickerProps = {
            suggestions: tslib_1.__spreadArrays(peopleSuggestions),
            isSuggestionsVisible: false,
            targetElement: null,
            onSuggestionSelected: _onSuggestionSelected,
            onRemoveSuggestion: _onSuggestionRemoved,
            suggestionsHeaderText: 'People suggestions',
            noResultsFoundText: 'No suggestions',
            onFloatingSuggestionsDismiss: undefined,
            showSuggestionRemoveButton: true,
            pickerWidth: '300px',
        };
        var selectedPeopleListProps = {
            selectedItems: tslib_1.__spreadArrays(peopleSelectedItems),
            removeButtonAriaLabel: 'Remove',
            onItemsRemoved: _onItemsRemoved,
            getItemCopyText: _getItemsCopyText,
            dropItemsAt: _dropItemsAt,
            onRenderItem: SelectedItem,
            replaceItem: _replaceItem,
        };
        var inputProps = {
            'aria-label': 'Add people',
        };
        return (React.createElement(React.Fragment, null,
            React.createElement(UnifiedPeoplePicker_1.UnifiedPeoplePicker, { componentRef: ref, selectedItemsListProps: selectedPeopleListProps, floatingSuggestionProps: floatingPeoplePickerProps, inputProps: inputProps, 
                // eslint-disable-next-line react/jsx-no-bind
                onInputChange: _onInputChange, 
                // eslint-disable-next-line react/jsx-no-bind
                onPaste: _onPaste })));
    };
    var ExampleSuggestionsModel = /** @class */ (function () {
        function ExampleSuggestionsModel(data) {
            var _this = this;
            this.resolveSuggestions = function (filterText, currentItems) {
                var filteredItems = [];
                if (filterText) {
                    filteredItems = _this._filterItemsByText(filterText);
                    filteredItems = _this._removeDuplicates(filteredItems, currentItems || []);
                }
                return _this._convertResultsToPromise(filteredItems);
            };
            this.suggestionsData = tslib_1.__spreadArrays(data);
        }
        ExampleSuggestionsModel.prototype.removeSuggestion = function (item) {
            var index = this.suggestionsData.indexOf(item);
            console.log('removing', item, 'at', index);
            if (index !== -1) {
                this.suggestionsData.splice(index, 1);
            }
        };
        ExampleSuggestionsModel.prototype._filterItemsByText = function (filterText) {
            var _this = this;
            return this.suggestionsData.filter(function (item) {
                var itemText = item.text || item.name;
                return itemText ? _this._doesTextStartWith(itemText, filterText) : false;
            });
        };
        ExampleSuggestionsModel.prototype._doesTextStartWith = function (text, filterText) {
            return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
        };
        ExampleSuggestionsModel.prototype._removeDuplicates = function (items, possibleDupes) {
            var _this = this;
            return items.filter(function (item) { return !_this._listContainsItem(item, possibleDupes); });
        };
        ExampleSuggestionsModel.prototype._listContainsItem = function (item, Items) {
            if (!Items || !Items.length || Items.length === 0) {
                return false;
            }
            return Items.filter(function (i) { return (i.text || i.name) === (item.text || item.name); }).length > 0;
        };
        ExampleSuggestionsModel.prototype._convertResultsToPromise = function (results) {
            return new Promise(function (resolve) { return setTimeout(function () { return resolve(results); }, 150); });
        };
        return ExampleSuggestionsModel;
    }());
});
//# sourceMappingURL=UnifiedPeoplePicker.WithEdit.Example.js.map