<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * OSB Application Module Method Model
 *
 * @package    OSB
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Model_Module_Method extends ORM_OSB {
	// This module doesnt keep track of column updates automatically
	protected $_created_column = FALSE;
	protected $_updated_column = FALSE;

	// Relationships
	protected $_belongs_to = array(
		'module'=>array(),
	);
	protected $_has_one = array(
		'record_id'=>array(),
	);
	protected $_has_many = array(
		'group'=>array('through'=>'group_method','foreign_key'=>'method_id')
	);

	protected $_sorting = array(
		'name'=>'ASC',
	);

	protected $status;

	// Temporarily adjust our name
	// @todo This is temporary until all our method names are colon delimited.
	protected function _load_values(array $values) {
		parent::_load_values($values);

		if (substr_count($this->name,'_') == 1 AND ! substr_count($this->name,':'))
			$this->name = str_replace('_',':',$this->name);
		elseif (substr_count($this->name,'_') > 1)
			throw HTTP_Exception::factory(501,'Method :id has double underscore',array(':id'=>$this->id));

		return $this;
	}

	public function controller_sub() {
		return substr_count($this->name,'_') ? substr($this->name,($x=strpos($this->name,'_')),strpos($this->name,':')-$x) : '';
	}

	public function controller() {
		return Kohana::classname(sprintf('Controller%s_%s',($this->directory() ? '_' : '').$this->directory(),$this->module->name).$this->controller_sub());
	}

	public function directory() {
		return substr($this->name,0,substr_count($this->name,'_') ? strpos($this->name,'_') : strpos($this->name,':'));
	}

	/**
	 * Calculate the description for this method on any menu link
	 */
	public function menu_display() {
		// @todo The test for value equal 1 is for legacy, remove when all updated.
		if ($this->menu_display AND $this->menu_display != 1)
			return $this->menu_display;
		else
			return sprintf('%s: %s',$this->module->name,$this->name);
	}

	public function method() {
		return substr($this->name,strpos($this->name,':')+1);
	}

	public function status($status=NULL) {
		if ($status)
			$this->status = $status;

		return $this->status;
	}

	public function url() {
		if (! preg_match('/:/',$this->name))
			return NULL;

		list($type,$action) = preg_split('/:/',$this->name,2);

		return URL::link($this->directory(),$this->module->name.$this->controller_sub().'/'.$action);
	}
}
?>
