<?php

abstract class TableCtrl extends Ctrl {



	abstract protected function getTable();



	abstract public function getDataSource();



	public function show() {
		return $this->build();
	}



	public function build() {
		// check data source
		$source = $this->getDataSource();
		if (!($source instanceof IDataSource)) {
			throw new Exception('no data source supplied');
		}

		// check table
		$table = $this->getTable();
		if (!($table instanceof Table)) {
			throw new Exception('no table supplied');
		}
		$columns = $table->getColumns();
		$id = $table->getId();

		// header
		if ($table->displayHeader) {
			$header = new TableRow();
			foreach ($columns as $field => $column) {
				$header->add($column->buildHeader($table, $field));
			}
			$table->add($header);
		}

		// body
		$i = 0;
		foreach ($source->fetch() as $record) {
			$row = new TableRow();
			foreach ($columns as $field => $column) {
				if (array_key_exists($field, $record)) {
					$column->buildCell($table, $row, $record, $field, $i);
				}
			}
			$table->add($row);
			++$i;
		}

		// footer
		if ($table->displayFooter) {
			$footer = new TableRow();
			foreach ($columns as $field => $column) {
				$footer->add($column->buildFooter($field));
			}
			$table->add($footer);
		}

		return $table;
	}



	public function orderBy($column, $descending) {
		$source = $this->getDataSource();
		$source->setOrder($column, ($descending === '1'));
		$table = $this->build();
		return $table;
	}



	public function addSelectionOnClick(Table $table, TableRow $row, $record, $field, $i) {
		$id = $table->getId();
		$value = $record[$field];
		++$i;
		$row->addListener(new ClickListener(new Behaviour("Table.select('$id', '$value', false, $i)")));
		return $record[$field];
	}



	public function setSelectionOnClick(Table $table, TableRow $row, $record, $field, $i) {
		$id = $table->getId();
		$value = $record[$field];
		++$i;
		$row->addListener(new ClickListener(new Behaviour("Table.select('$id', '$value', true, $i)")));
		return $record[$field];
	}



	public function select($tableCtrl, $value) {
		$t = ActionService::execAction($tableCtrl . '/show');
        $t->value = $value;
	}



	public function selectOne($tableCtrl, $value, $i) {
		$t = ActionService::execAction($tableCtrl . '/show');
// FIXME JSON here
        if ($t->value) {
            $t->value = '[' . trim($t->value, '[] ,') . ', ' . $value . ']';
        } else {
            $t->value = $value;
        }
		$this->response->setTableValue($t->getId(), $value);
		$this->response->markRowCells($t->getId(), $i, 1);
	}



} // class TableCtrl

?>