/*
 *  Copyright (C) 2006-2019  Ronald Blankendaal
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package org.dbgl.gui.controls;

import java.util.List;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import org.dbgl.model.entity.ITitledEntity;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;


public class AutoSelectCombo {

	private final Combo combo_;

	private int currentLength_;
	private boolean mutex_;

	public AutoSelectCombo(Composite composite, Object layoutData, List<ITitledEntity> possibleValues) {
		combo_ = new Combo(composite, SWT.NONE);
		combo_.setLayoutData(layoutData);
		combo_.setVisibleItemCount(15);
		possibleValues.stream().forEach(x -> combo_.add(x.getTitle()));
		combo_.pack();

		currentLength_ = 0;
		mutex_ = false;

		combo_.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent event) {
				if (!mutex_) {
					String text = combo_.getText();
					int newLength = text.length();
					if (newLength > currentLength_) {
						OptionalInt opt = IntStream.range(0, combo_.getItemCount()).filter(i -> combo_.getItem(i).toLowerCase().startsWith(text.toLowerCase())).findFirst();
						if (opt.isPresent()) {
							mutex_ = true;
							combo_.setText(text + combo_.getItem(opt.getAsInt()).substring(newLength));
							combo_.setSelection(new Point(newLength, combo_.getText().length()));
							mutex_ = false;
						}
					}
					currentLength_ = newLength;
				}
			}
		});
	}

	public String getText() {
		return combo_.getText();
	}

	public void setText(String text) {
		combo_.setText(text);
		currentLength_ = text.length();
	}

	public Control getControl() {
		return combo_;
	}
}