package jp.ac.kyutech.mns.ist.util;
import java.lang.reflect.Field;
import java.util.ArrayList;

import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;


public class SelectableTableModel<E> extends DefaultTableModel/* implements TableModel*/ {
	private static final long serialVersionUID = -6481352300961323271L;
	public static String empty = "";
	ArrayList<E> adata;
	String[] labels;
	String[] fields;
	public SelectableTableModel(ArrayList<E> data, String[] lab, String[] fie) {
		adata = data;
		labels = lab;
		fields = fie;
	}
	@Override
	public void addTableModelListener(TableModelListener arg0) {
	}
	@Override
	public Class<?> getColumnClass(int col) {
		if (getValueAt(0, col)==null) return String.class;
        return getValueAt(0, col).getClass();
	}
	@Override
	public int getColumnCount() {
		return labels.length;
	}
	@Override
	public String getColumnName(int arg0) {
		return labels[arg0];
	}
	@Override
	public int getRowCount() {
		if (adata != null)
		return adata.size();
		else return 0;
	}
	@Override
	public Object getValueAt(int row, int col) {
		if (col == -1) return adata.get(row);
		if (fields[col].length()==0) {
			return empty;
		}
		try {
			E a = adata.get(row);
			Field f = a.getClass().getField(fields[col]);
			return f.get(a);
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
		return null;
	}
	@Override
	public void setValueAt(Object obj, int row, int col) {
		if (fields[col].length()==0) {
			return;
		}
		try {
			E a = adata.get(row);
			Field f = a.getClass().getField(fields[col]);
			f.set(this, obj);
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	@Override
	public boolean isCellEditable(int row, int col) {
		if (fields[col].length()==0) {
			return true;
		}
		return false;
	}

	@Override
	public void removeTableModelListener(TableModelListener arg0) {
//		super.removeTableModelListener(arg0);
	}

}
