<?php
class APIFunction extends WatchDogAppModel {

	public $useTable = 'functions';

	public $belongsTo = array(
		'FunctionCollection' => array(
			'className' => 'WatchDog.FunctionCollection',
			'foreignKey' => 'function_collection_id'));

	public $hasOne = array(
		'Documentation' => 'Upload doc docx pdf');

	public $hasMany = array(
		'FunctionParams' => array(
			'className' => 'WatchDog.FunctionParam',
			'foreignKey' => 'function_id',
			'fields' => array(
				'id', 'type', 'default', 'options')));


# ~ Get the list of all calls  - - - - - - - - - - - - - - - - - - - - - - - - #
	public function get() {

		# Create place for functions that do not belong anywhere
		$results = array(null => array(
			'id' => null,
			'name' => null,
			'functions' => array()
		));

		# Get the collections and make sure the result is properly ordered
		$collections = $this->model('FunctionCollection')->find('all', array(
			'order' => 'ordering',
			'fields' => array(
				'id', 'name', 'ordering')
		));

		# Initialize the collections in the results
		foreach($collections as $collection) {
			$results[$collection['FunctionCollection']['id']] = reset($collection);
			$results[$collection['FunctionCollection']['id']]['functions'] = array();
		}

		# Get the functions
		$functions = $this->find('all', array(
			'fields' => array(
				'id', 'function_collection_id', 'url', 'description',
				'http_method', 'enc_type', 'body', 'ordering')
		));

		# Pack the results
		foreach($functions as $function) {

			# Handle tha params
			$params = array();
			foreach($function['FunctionParams'] as $parameter) {

				# Clear options
				$options = array();
				if(!empty($parameter['options'])) foreach(explode("\n", rtrim($parameter['options'])) as $option) {
					$options[] = trim($option);
				}

				# Set the parameters
				$params[] = array(
					'id' => $parameter['id'],
					'type' => $parameter['type'],
					'default' => $parameter['default'],
					'options' => $options
				);
			}

			# Add the function
			$collectionId = $function['APIFunction']['function_collection_id'];
			$function = reset($function);
			$function['params'] = $params;

			$results[$collectionId]['functions'][] = $function;
		}

		# Remove empty ones
		foreach($results as $i => $collection) {
			if(empty($collection['functions'])) {
				unset($results[$i]);
			}
		}

		return array_values($results);
	}

# ~ Update a single function - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function update($data) {

		# Save basic info
		$this->save($data);

		return true;
	}


}
