package industries.doublehelix.conditionalfilter.gui.filtersettings;

import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

import industries.doublehelix.conditionalfilter.filtertypes.flat.FixedValuesStringFilter;
import industries.doublehelix.conditionalfilter.filtertypes.flat.StringFilter;
import industries.doublehelix.conditionalfilter.filtertypes.flat.StringFilter.StringFilterMode;

public class FixedValuesStringFilterSettingsPanel extends FilterSettingsPanel implements ActionListener {
	private static final long serialVersionUID = -6614004532630323774L;
	
	JComboBox<StringFilterMode> filterMode = new JComboBox<>();
	JComboBox<String> text = null;//ew JComboBox<>();
	
	public FixedValuesStringFilterSettingsPanel(FixedValuesStringFilter filter, int preferredContentHeight) {
		super(filter, preferredContentHeight);
		
		StringFilterMode[] modes = {StringFilterMode.IS, StringFilterMode.ISNOT};
		filterMode.setModel(new DefaultComboBoxModel<>(modes));
		//filterMode.setMaximumSize(filterMode.getPreferredSize());
		filterMode.setSelectedItem(filter.getFilterMode());
		filterMode.addActionListener(this);
		
		text = new JComboBox<>(filter.getPossibleValues().toArray(new String[filter.getPossibleValues().size()]));
		if (filter.getString() == null || filter.getString().isEmpty()) {
			// init to first in list
			text.setSelectedIndex(0);
			filter.setString(text.getItemAt(0));
		} else {
			text.setSelectedItem(filter.getString());
		}
		text.addActionListener(this);

		setPreferredHeightToComponents(text, filterMode);
		
		
		this.add(filterMode);
		this.add(Box.createHorizontalStrut(5));
		this.add(text);
		GridBagConstraints c = new GridBagConstraints();
		c.weightx = 1.0;
		this.add(Box.createHorizontalGlue(), c);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if (source == filterMode) {
			StringFilter castedFilter = (FixedValuesStringFilter)this.filter;
			StringFilterMode selectedFilterMode = (StringFilterMode)filterMode.getSelectedItem();
			if (selectedFilterMode != castedFilter.getFilterMode()) {
				castedFilter.setFilterMode(selectedFilterMode);
			}
		} else if (source == text) {
			StringFilter castedFilter = (FixedValuesStringFilter)this.filter;
			String selectedText = (String)text.getSelectedItem();
			castedFilter.setString(selectedText);
		}
	}
}
