<?php
App::uses('AppFrontController', 'Controller');

class AppApiController extends AppFrontController {
	public $components = [ 'Api' ];
	public $name = 'Api';

	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow();

		# Log the request
		$this->Api->storedRequest = ClassRegistry::init('LogApi')->checkRequest($this->request);

		# Make sure that action exist
		try {
			$method = new ReflectionMethod($this, $this->request->action);
			if ($method->class !== get_class($this) || !$method->isPublic()) {
				throw new APIHardException(404, 'Unknown API function');
			}

			# Call before execute
			$this->beforeExecute();

			# Call the method
			call_user_func_array([ $this, $this->request->action ], $this->request->params['pass']);

		} catch (Exception $ex) {
			$this->Api->handleException($ex);
		}

		$this->failure(__('Action not implemented'));
	}

	/**
	 * Called just before api action run
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	protected function beforeExecute() {
	}

	/**
	 * Get the path to the image.
	 *
	 * @param    $image
	 *                The image array or path.
	 *
	 * @returns    Proper path to the image, or null if the image is not available.
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	protected function image($image) {

		# Handle array
		if (is_array($image)) {
			$image = @$image['file'];
		}

		# Return the path
		return $image ? FULL_BASE_URL . $image : null;
	}

	/**
	 * Return $value or null, if $value is empty.
	 *
	 * @param    $value
	 *                The value to test.
	 *
	 * @returns    Supplied $value if it is not empty, null if empty.
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	protected function nullable($value) {
		return $value ? $value : null;
	}

	/**
	 * Failed api action response
	 *
	 * @param $message
	 */
	protected function failure($message = '', $code = 200) {
		if ($message instanceof APIHardException) {
			if (Configure::read('debug')) {
				$message = $message->getMessage();
				$code = 500;
			}
		}

		$this->Api->build(
			null,
			[
				'success' => false,
				'message' => $message,
				'data'    => null
			],
			[],
			[
				'code' => $code
			]
		);
	}

	/**
	 * Success response
	 *
	 * @param      $data
	 * @param null $message
	 */
	protected function success($data = null, $message = null, $code = 200) {
		if ($data == null) {
			$data = new \StdClass();
		}

		$this->Api->build(
			null,
			[
				'success' => true,
				'message' => $message,
				'data'    => $data
			],
			[],
			[
				'code' => $code
			]
		);
	}

	public function validatePost($fields) {
		if (!$this->request->is('post')) {
			$this->failure(__('Invalid request'), 400);
		}

		foreach ($fields as $field) {
			if (!array_key_exists($field, $this->request->data)) {
				$this->failure(__('Field %s is missing'), 400);
			}
		}
	}

}
