/*
 * Copyright 2009-2010 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.lisp.swing;

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import net.morilib.lisp.ConsIterator;
import net.morilib.lisp.Datum;
import net.morilib.lisp.LispMessage;
import net.morilib.lisp.LispUtils;
import net.morilib.lisp.subr.SubrUtils;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2012/04/01
 */
public class LispJTable extends LightweightGUIElement {

	//
	JTable table;

	/**
	 * 
	 * @param table
	 */
	public LispJTable(JTable table) {
		this.table = table;
	}

	//
	static JTable makeTable(Datum d, LispMessage mesg) {
		ConsIterator itr = new ConsIterator(d);
		final List<List<Datum>> mdl = new ArrayList<List<Datum>>();
		final int[] cl = new int[1];
		List<Datum> l;

		cl[0] = 0;
		while(itr.hasNext()) {
			mdl.add(l = LispUtils.consToList(itr.next(), mesg));
			if(l.size() > cl[0])  cl[0] = l.size();
		}
		SubrUtils.checkProper(itr, d, mesg);

		return new JTable(new AbstractTableModel() {

			@Override
			public int getRowCount() {
				return mdl.size();
			}

			@Override
			public int getColumnCount() {
				return cl[0];
			}

			@Override
			public Object getValueAt(int row, int col) {
				if(row < 1 || row > getRowCount()) {
					return null;
				} else if(col < 1 || col > getColumnCount()) {
					return null;
				} else if(col > mdl.get(row - 1).size()) {
					return null;
				} else {
					return mdl.get(row - 1).get(col - 1);
				}
			}

		});
	}

	/* (non-Javadoc)
	 * @see net.morilib.lisp.swing.ILispComponent#getComponent()
	 */
	@Override
	public JComponent getComponent() {
		return table;
	}

	/* (non-Javadoc)
	 * @see net.morilib.lisp.swing.GUIElement#getAWTComponent()
	 */
	@Override
	public Component getAWTComponent() {
		return table;
	}

	/* (non-Javadoc)
	 * @see net.morilib.lisp.Datum2#toDisplayString(java.lang.StringBuilder)
	 */
	@Override
	public void toDisplayString(StringBuilder buf) {
		buf.append("#<gui-table>");
	}

}
