/*
 * Copyright (c) 2007
 * OpenRules, Inc.
 */

/**
 * This class supports dynamic tables inside OpenRules Forms. It serves as 
 * a base class for concrete table managers - see example "PartyManager"
 * Only two abstract methods should be overwritten:
 * - getHeaderLayoutName() that returns a name of the table header from an Excel file
 * - getRowLayout(Checkable row) that returns a name of the table row from an Excel file
 *  
 */
package com.openrules.forms.gui.impl;

import java.util.ArrayList;
import java.util.Iterator;

import com.openrules.forms.gui.IGUIComponent;
import com.openrules.forms.gui.impl.GUIComponent;
import com.openrules.forms.gui.impl.TableLayout;
import com.openrules.ruleengine.OpenRulesEngine;
import com.openrules.types.Checkable;

abstract public class DynamicTable {
	
	ArrayList rows;
	Checkable currentRow;
	OpenRulesEngine engine;

	public DynamicTable(OpenRulesEngine engine) {
		rows = new ArrayList();
		this.engine = engine;
	}
	
	public void addNewRow(Checkable row) {
		currentRow = row;
		rows.add(row);
	}
	
	public void deleteRow(Checkable row) {
		rows.remove(row);
	}
	
	public void deleteCheckedRows(String attribute) {
		for(Iterator it = rows.iterator (); it.hasNext (); ) { 
			Checkable row = (Checkable)it.next();
			if (row.isChecked(attribute)) {
				it.remove();
			}
		}
	}

	public ArrayList getRows() {
		return rows;
	}

	public void setRows(ArrayList rows) {
		this.rows = rows;
	}

	public Checkable getCurrentRow() {
		return currentRow;
	}

	public void setCurrentRow(Checkable currentRow) {
		this.currentRow = currentRow;
	}
	
	public Checkable getFirstCheckedRow(String attribute) {
		for(Iterator it = rows.iterator (); it.hasNext (); ) { 
			Checkable row = (Checkable) it.next();
			if (row.isChecked(attribute)) {
				return row;
			}
		}
		if (rows.size() > 0)
		   return (Checkable) rows.get(0);
		else
			return null;
	}
	
	/**
	 *  @return a table header layout
	 */ 
	abstract public String getHeaderLayoutName(); 
	
	/**
	 *  @return a table row layout
	 */ 
	abstract public String getRowLayoutName();

	public IGUIComponent createTable() {
		IGUIComponent table = (TableLayout) engine.run(getHeaderLayoutName());
		Iterator it = rows.iterator();
		while( it.hasNext() )  {
		   Checkable row = (Checkable) it.next();
		   table = TableLayout.merge(table, (GUIComponent)engine.run(getRowLayoutName(),row));
		}
		return table;
	}

	public OpenRulesEngine getEngine() {
		return engine;
	}

	public void setEngine(OpenRulesEngine engine) {
		this.engine = engine;
	}

}