<?php

/**
 * Server side action call
 *
 * Produces a Javascript code that calls controller on event occurence.
 * Can be called directly from server side as well.
 *
 * @version DR1.5
 */
class Action implements IActionAdapter {



	protected $actionString = '';
	protected $args = array();



	/**
	 * Creates action configured with action string and args
	 *
	 * @param string action string
	 * @param mixed argument or array of arguments
	 */
	public function __construct($actionString, $args = array('')) {
		$this->actionString = $actionString;
		$this->args = (array)$args;
	}



	/**
	 * Returns Javascript code that invokes server side action call
	 *
	 * @return string Javascript
	 */
	public function __toString() {
		$a = implode(', ', $this->args);
		return "call('{$this->actionString}', [$a]);";
	}



	/**
	 * Converts action string to Action object
	 *
	 * @param string action string
	 * @param mixed argument or array of arguments
	 */
	public static function buildAction($action, $args = array()) {
		if ($action instanceof Action) {
			return $action;
		} elseif (!is_string($action)) {
			throw new Exception('action is neither of not of type Action nor string');
		}
		return new Action($action, $args);
	}



	/**
	 * Invokes action call from server side and returns Controller action output.
	 */
	public function run() {
		if (!$this->actionString) {
			throw new Exception('action string not defined');
		}
		return ActionService::execAction($this->actionString, (array)$this->args);
	}



	public function getActionString() {
		return $this->actionString;
	}



	public function setActionString($action) {
		$this->actionString = $actionString;
	}



	public function getArgs() {
		return $this->args;
	}



	public function setArgs($args = array()) {
		$this->args = (array)$args;
	}



	public function pop() {
		return array_pop($this->args);
	}



	public function push($a) {
		return array_push($this->args, $a);
	}



	public function shift() {
		return array_shift($this->args);
	}



	public function unshift($a) {
		return array_unshift($this->args, $a);
	}



} // class Action

?>