<?php

class ApiController extends Controller
{

	static function actionIndex()
	{
		$request = json_decode(file_get_contents('php://input'), 1);

//		Отладка:
//		$request = array('method' => 'categories');
//		$request = array('method' => 'location');
//		$request = array('method' => 'points');
//		$request = array('method' => 'point', 'data' => '{"id":12}');

		if (!is_array($request)) {
			self::error('Bad request!');
		}

		$method = isset($request['method']) ? $request['method'] : NULL;
		$data = isset($request['data']) ? json_decode($request['data'], TRUE) : NULL;
		$environment = isset($request['environment']) ? $request['environment'] : NULL;
		$answer = NULL;

		App::log('apiController', array($method, $data, $environment));

		switch ($method) {
			case 'categories':
				$answer = self::getCategories();
				break;
			case 'points':
				$answer = self::getPoints($data);
				break;
			case 'point':
				$answer = self::getPoint($data);
				break;
			case 'location':
				$answer = self::getLocation();
				break;
			default:
				self::error('Unknown method!');
				break;
		}

		self::renderPartial('json.php', array('data' => $answer));
	}

	/**
	 * Точки
	 */
	static private function getPoints($data)
	{
		$minEditDate = isset($data['time']) ? intval($data['time']) : 0;

		if ($minEditDate == 0) {
			$points = Point::model()->getSortedByDistance(App::$userGeo['lat'], App::$userGeo['lng']);
		} else {
			$points = Point::model()->getAllPublished(false, $minEditDate);
		}

		$categories = Category::model()->getAll(array('order' => 'ord ASC', 'asArray' => true));

		$result = array();

		foreach ($points as $point) {
			$tempPoint['id'] = $point->id;
			$tempPoint['name'] = $point->name;
			$tempPoint['lat'] = $point->lat;
			$tempPoint['lng'] = $point->lng;
			$tempPoint['categoryId'] = $point->categoryId;
			$tempPoint['status'] = $point->status;

			$result[] = $tempPoint;
		}

		return array(
			'status' => 'success',
			'data' => array(
				'points' => $result,
				'timestamp' => time(),
			),
			'geo' => App::$userGeo,
		);
	}

	/**
	 * Точка
	 */
	static private function getPoint($data)
	{
		$id = isset($data['id']) ? intval($data['id']) : NULL;

		if (!$id) {
			self::error('Broken request!');
		}

		$point = Point::model()->getByPK($id);

		if (!$point->id) {
			self::error('Unknown point!', 404);
		}

		$point->description = Helper::replaceLinks($point->description);
		$point->name = htmlspecialchars($point->name);
		$imgs = $point->photos;
		$photosCount = 1;

		if ($point->img == '' && !empty($imgs)) {
			$img = array_shift($imgs);
			$point->img = $img->name;
		}

		$imgs = $point->photos;
		if (!empty($imgs)) {
			$tmp = array();
			$photosCount = count($imgs);
			foreach ($imgs as $img) {
				$tmp[] = $img->name;
			}
			$point->images = $tmp;
		}

		$extraParams = $point->getExtraParams();
		if (!empty($extraParams)) {
			$tmp = array();
			foreach ($extraParams as $extraParam) {
				$tmp[] = array($extraParam->name, $extraParam->value);
			}
			$point->extraParams = $tmp;
		}

		$categories = Category::model()->getAll(array('order' => 'ord ASC', 'asArray' => true));

		$point->categoryIcon = $categories[$point->categoryId]['icon'];
		$point->categoryName = $categories[$point->categoryId]['name'];
		$point->photosCount = $photosCount;
		$point->inFavorites = Favorite::model()->checkIsMy($id);
		$point->iLike = Like::model()->checkIsMy($id);

		return array('status' => 'success','data' => $point->getValues(), 'geo' => App::$userGeo);
	}

	/**
	 * Категории
	 */
	static private function getCategories()
	{
		$categories = Category::model()->getAll(array('order' => 'ord DESC', 'asArray' => true, 'noKeys' => true));

		$categories[] = array(
			"id" => "0",
			"name" => "Все точки",
			"icon" => "/ico/all.png",
			"ord" => "0"
		);

		$categories = array_reverse($categories);

		return array('status' => 'success','data' => $categories, 'geo' => App::$userGeo);
	}

	static private function getLocation()
	{
		return array('status' => 'success','data' => App::$userGeo);
	}

	static private function error($message = FALSE, $code = 500)
	{
		$answer = array('status' => 'error', 'code' => $code);

		if ($message) {
			$answer['message'] = $message;
		}

		self::renderPartial('json.php', array('data' => $answer));
		die;
	}

	static function actionDump()
	{
		$key = App::getParam('key');
		$localKey = md5('salt'+substr(time(), 0, 8)+'salt2');

		if ($key != $localKey) {
			App::error404();
		}

		$categories = self::getCategories();
		$categories = $categories['data'];
		$points = self::getPoints($data);
		$points = $points['data'];

		$dataset = array(
			'categories' => $categories,
			'points' => $points,
			'timestamp' => time(),
		);

		$result = array('status' => 'success','data' => $dataset);

		self::renderPartial('json.php', array('data' => $result));
	}
}
