<?php
class LogApi extends AppModel {
	public $name = 'LogApi';
	public $useTable = "log_api";
	public $order = 'LogApi.created DESC';

	public $isModule = false;
	public $displayField = 'ip_address';


	public $serializedFields = array('post_data', 'passed_data', 'named_params');

	public function isAddable() {
		return false;
	}

	public function isEditable($id = null) {
		return false;
	}

	public function isDeletable($id = null) {
		return false;
	}

	public function afterFind($results, $primary = false) {
		foreach($results as $key => $result) {
			foreach($this->serializedFields as $field) {
				if(isset($results[$key][$this->alias][$field])) {
					$results[$key][$this->alias][$field] = print_r(unserialize($result[$this->alias][$field]), true);
				}
			}
		}

		return $results;
	}


	public function checkRequest($request) {

		# Save
		$savedRequest = $this->logRequest($request);

		# Check request validity
		$requestInvalid = false;
		if($requestInvalid) {
			throw new Exception('Request invalid');
		}
		return $savedRequest['LogApi']['id'];
	}

	private function logRequest(CakeRequest $request) {
		$data = array(
			'locale' => $request->params['language'],
			'platform' => $this->getPlatform(env('HTTP_USER_AGENT')),
			'controller' => $request->params['controller'],
			'controller_action' => $request->params['action'],
			'ip_address' => $request->clientIp(),
			'user_agent' => env('HTTP_USER_AGENT'),
			'post_data' => serialize($request->data),
			'passed_data' => serialize($request->params['pass']),
			'named_params' => serialize($request->params['named']),
			'body' => $request->input()
		);

		# Common headers
		$headerFields = array(
			'DeviceType'		=> 'device_type',
			'DeviceId'			=> 'device_key',
			'RegistrationKey'	=> 'registration_key',
			'AuthToken'			=> 'auth_token'
		);

		$headers = array_fill_keys(array_values($headerFields), null);
		foreach($headerFields as $field => $normalizedField) {
			$headers[$field] = $request->header($field);
		}
		$data['headers'] = json_encode($headers);

		# Save special fields separatelly
		foreach(array('version', 'timestamp', 'device_key', 'token') as $key) {
			if(!empty($request->data[$key])) {
				$data[$key] = $request->data[$key];
			}
		}

		# Save with no callbacks to speed up things
		return $this->save(
			$data,
			array(
				'callbacks' => false,
				'validate' => false)
		);
	}

	public function getPlatform($userAgent) {

		# Map the devices to their signatures
		$map = array(

			'ios' => array(
				'Darwin',
				'iPhone',
				'iPad'
			),

			'android' => array(
				'Apache-HttpClient/UNAVAILABLE.*java',
				'Android',
				'Dalvik'
			)
		);

		# Get the appropriate link
		$device = null;
		foreach($map as $name => $regexps) {
			foreach($regexps as $regexp) {
				if(preg_match("~{$regexp}~ i", $userAgent)) {
					$device = $name;
					break(2);
				}
			}
		}

		return $device;
	}

}
