package pbl2011.gui;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import pbl2011.common.CommonConst;
import pbl2011.model.ClassNode;
import pbl2011.mvc.Model;

/**
 * 詳細画面の抽象クラス
 * このクラスを実装し、操作・属性・関連タブを作る
 * @author 10745104 Y.Ishii
 *
 */
public abstract class DetailForm extends JComponent implements CommonConst {

	Model myModel;
	public DetailForm(Model m) {
		myModel = m;
		setLayout(new BorderLayout());
		initialize();
	}

	protected JTable table = new JTable();
	protected JTableHeader tableHeader;
	protected ClassNode clone;
	protected DefaultTableModel tableModel;
	protected void drawOne() {
		String[][] data = getTableData();
		String[] tableCol = getTableCol();

		tableModel = new DefaultTableModel(data, tableCol);
		tableModel.addTableModelListener(new TableModelListener() {

			@Override
			public void tableChanged(TableModelEvent e) {

				updateModel(e.getFirstRow());

			}
		});
		table.setModel(tableModel);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		int i = 0;
		for (String[] s : getComboData()) {
			if (s != null) {
				createCombo(s, i);
			}
			i++;
		}
	}

	abstract List<String[]> getComboData();

	private void createCombo(String[] list, int i) {
		// comboの設定
		JComboBox cb = new JComboBox(list);
		cb.setEditable(true);
		cb.setBorder(BorderFactory.createEmptyBorder());

		TableColumnModel tcm = table.getColumnModel();
		TableColumn tc = tcm.getColumn(i); // ｺﾝﾎﾞにする行(左から0)
		tc.setCellEditor(new DefaultCellEditor(cb)); // 編集
	}

	abstract void updateModel(int sc);

	abstract String[] getTableCol();

	protected void changeLine(){};

	abstract String[][] getTableData();

	protected void initialize() {

		removeAll();
		drawOne();
		table.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				changeLine();
			}
		});

		tableHeader = table.getTableHeader();
		add(tableHeader, BorderLayout.NORTH);
		add(table, BorderLayout.CENTER);
		validate();
	}

	int getSelectedRow() {
		return table.getSelectedRow();
	}

	int getRowNum() {
		return table.getRowCount();
	}
	protected void setClassNode(ClassNode cn) {
		clone = cn;
	}
}
