package leaf.ui;

import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;

import com.evolute.utils.tables.BaseTable;
import com.evolute.utils.tables.VectorTableModel;

public class SimpleTable<ROW_CLASS> extends JScrollPane
{

	private static final long serialVersionUID = 1L;

	private final VectorTableModel<ROW_CLASS> model;
	
	private final BaseTable table;
	
	public SimpleTable( String ... columnName )
	{
		model = new VectorTableModel<ROW_CLASS>( columnName );
		table = new BaseTable( model );
		setViewportView(table);
		setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	}
	
	public VectorTableModel<ROW_CLASS> getModel()
	{
		return model;
	}
	
	public BaseTable getTable()
	{
		return table;
	}
	
	public void setTitle(String title)
	{
		setBorder(BorderFactory.createTitledBorder(title));
	}
	
	public void addListSelectionListener(ListSelectionListener listener){
		table.getSelectionModel().addListSelectionListener(listener);
	}
	
	public void setRows( Vector<ROW_CLASS> rows )
	{
		model.setValues( rows );
	}
	
	public ROW_CLASS getSelectedRow()
	{
		ROW_CLASS result = null;
		int index = table.getSelectedRow();
		if( index > -1 )
		{
			result = model.getRowAt( index );
		}
		return result;
	}
	
	public List<ROW_CLASS> getSelectedRows()
	{
		List<ROW_CLASS> result = null;
		int [] index = table.getSelectedRows();
		for( int i = 0; i < index.length; ++i )
		{
			result.add( model.getRowAt( index[i] ) );
		}
		return result;
	}
	
	public void clear()
	{
		model.clearAll();
	}
	
}
