package de.thpeetz.kontor.common.views;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.vaadin.flow.component.combobox.MultiSelectComboBox;
import com.vaadin.flow.component.combobox.MultiSelectComboBox.AutoExpandMode;
import com.vaadin.flow.component.customfield.CustomField;
import com.vaadin.flow.component.textfield.TextField;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SearchFilterField extends CustomField<SearchFilter> {

    private final TextField searchField = new TextField();
    private final MultiSelectComboBox<FilterOption> filterField = new MultiSelectComboBox<>();
    private final List<FilterOption> filterOptions = new LinkedList<>();

    public SearchFilterField() {
        searchField.setPlaceholder("Search");
        searchField.setClearButtonVisible(true);
        filterField.setPlaceholder("Filter");
        filterField.setClearButtonVisible(true);
        filterField.setItemLabelGenerator(FilterOption::getName);
        filterField.setAutoExpand(AutoExpandMode.BOTH);
        add(searchField, filterField);
    }

    @Override
    protected SearchFilter generateModelValue() {
        SearchFilter filter = new SearchFilter();
        if (searchField.getValue() != null) {
            filter.setSearchTerm(searchField.getValue());
        }
        Set<FilterOption> filterOptions = filterField.getValue();
        for (FilterOption filterOption : filterOptions) {
            filter.addFilter(filterOption);
        }
        log.info("use searchfilter: {}", filter);
        return filter;
    }

    @Override
    protected void setPresentationValue(SearchFilter searchFilter) {
        log.info("display filter: {}", searchFilter);
        if (searchFilter == null) return;
        searchField.setValue(searchFilter.getSearchTerm());
    }

    public void addFilter(String optionName) {
        FilterOption filterOption = new FilterOption(optionName, true);
        filterOptions.add(filterOption);
        filterField.setItems(filterOptions);
    }
}
