package hiro.yoshioka.ui.multispan;

import java.util.ArrayList;

import hiro.yoshioka.sdh.HeaderType;
import hiro.yoshioka.sdh.ResultSetDataHolder;

import javax.swing.table.DefaultTableModel;

public class ResultSetTableModel extends DefaultTableModel {
	ResultSetDataHolder rdh;
	int[] percentIdx = new int[0];

	public String getColumnName(int column) {
		if (rdh == null) {
			return "";
		}
		return rdh.getKey()[column].toString();
	}

	@Override
	public void setValueAt(Object aValue, int row, int column) {
		if (rdh == null || aValue.equals(rdh.getRow(row)[column])) {
			return;
		}
		try {
			rdh.createBackUp(row);
			// aValue = rdh.getYukoString(column, aValue.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		rdh.changeString(row, column, (String) aValue);
		if (rdh.reseted(row)) {
			rdh.changeStatus(row, HeaderType.NO_EDITION);
		} else {
			rdh.changeStatus(row, HeaderType.UPDATE);
		}
		super.setValueAt(aValue, row, column);
		super.setValueAt(rdh.getStringData(row, "ROW"), row, 0);
	}

	public boolean isCellEditable(int row, int column) {
		if (column == 0 || !rdh.hasResultSetMetaData()) {
			return false;
		}
		return true;
	}

	public ResultSetTableModel(ResultSetDataHolder rdh) {
		super(rdh.getKey(), 0);
		this.rdh = rdh;
		for (int i = 0; i < rdh.getRowCount(); i++) {
			addRow(rdh.getRow(i));
		}
		ArrayList<Integer> list = new ArrayList<Integer>();
		String[] keys = rdh.getKey();
		for (int i = 0; i < keys.length; i++) {
			if (keys[i].indexOf('%') >= 0) {
				list.add(i);
			}
		}
		percentIdx = new int[list.size()];
		for (int i = 0; i < percentIdx.length; i++) {
			percentIdx[i] = list.get(i);
		}
	}

	public int[] getPercentIdx() {
		return percentIdx;
	}

	public void deleteRows(int[] indices) {
		for (int i = 0; i < indices.length; i++) {
			try {
				rdh.createBackUp(indices[i]);
				// aValue = rdh.getYukoString(column, aValue.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rdh.changeStatus(indices[i], HeaderType.DELETE);
			super.setValueAt(rdh.getStringData(indices[i], "ROW"), indices[i],
					0);
		}
	}
}