<?php
class Api_CalendarController extends Zend_Controller_Action 
{
	
	public function init()
	{
		//TODO: extend authentication to support multiple user levels/roles/groups 
		require_once 'application/models/api.php';
		require_once 'application/models/calendar.php';
		
		$this->api = new api();
		
		$this->view->baseUrl = $this->_request->getBaseUrl();
		$this->view->appBaseUrl = $this->_request->getBaseUrl() . (strpos($this->_request->getBaseUrl(),'index.php')?'':'/index.php');
		$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
		$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->_request->module == 'default'?'':DIRECTORY_SEPARATOR . $this->_request->module);
		
		$this->_helper->viewRenderer->setNoRender();
		
		$this->restserver = new Zend_Rest_Server();
		$this->restserver->setClass('api');

		// Load all the params
		$this->requestParams = $this->getRequest()->getParams();
		
		// Use Cookie auth
		if( !Atmail_FormAuth::authenticated() )
		{
			
			// we have most probably timed out, so lets kick them to the timeout bootstrap page
			// this will poison json responses, which will fire the php.error ( or ajax.error ) which can detect the special page
			$this->_forward('timeout', 'mail', 'api');
			return;

		} else {
			
			// Load the session
			$this->session = new Zend_Session_Namespace(ATMAIL_NAMESPACE);
			$this->userData = Zend_Auth::getInstance()->getStorage()->read();
			$this->userData = Atmail_Password::processUser($this->userData);

			// Load the system settings
			$this->_globalConfig = Zend_Registry::get('config')->global;

			// Find the users settings ( used for theme )
			$this->view->UserSettings = Zend_Registry::get('UserSettings');

			// Used to determine the contact in the global addressbook
			$this->view->Account = $this->userData['Account'];

			// If no defined CalDavUser/CalDavPass in the UserSettings table, revert to the current logged in session details
			if(empty($this->UserSettings['CalDavUser']))
				$CalDavUser = $this->userData['Account'];
			else
				$CalDavUser = $this->UserSettings['CalDavUser'];

			// Fetch the CalDAV password
			if(empty($this->UserSettings['CalDavPass']))
				$CalDavPass = $this->userData['password'];
			else
				$CalDavPass = $this->UserSettings['CalDavPass'];

			$this->_calendar = new calendar(array('Timezone' => $this->UserSettings['TimeZone'], 'Type' => $this->view->UserSettings['CalDavType'], 'URL' => $this->UserSettings['CalDavUrl'], 'Account' => $CalDavUser, 'Password' => $CalDavPass, 'Calendar' => "calendar", 'home', 'largeInstall' => '0') );

		}
		
						
	} 
	

	public function listAction() {

		if(isset($param['start']))
		{
			$this->view->params['start'] = date('Y-m-d', $param['start']);
		}
		else
		{
			$this->view->params['start'] = date('Y-m-d', time());
		}

		if(isset($param['end']))
		{
			$this->view->params['end'] = date('Y-m-d', $param['end']);
		}
		else
		{
			$this->view->params['end'] = date('Y-m-d', time() + (60*60*24*365));
		}
		
		$start = "{$this->view->params['start']} 00:00:00";
		$end = "{$this->view->params['end']} 23:59:59";
		
		$this->calNames = $this->_calendar->getCalNames($this->_caldav_server, $this->caldav_URL);
		
				if($cutoffdate != 0)
				{		
					$cutoff = new Date($cutoffdate);
					$cutoffstr = $cutoff->getTime();
					$now = new Date();
					$nowstr = $now->getTime();
				}
				else
				{
					$cutoffstr = '';
					$nowstr = '';
				}
				
		$events = $this->_calendar->getPushRange($cutoffstr, $nowstr, '', '', false);
		
		foreach($events as $event)	{
			$eventArray[] = $this->_calendar->get_record($event['id'], $event['relative_href']);
		}
		

		// If we are a JSONP request, wrap in a function
		if( !empty($this->requestParams['jsoncallback']) && !empty($this->_globalConfig['jsonpAPI']) )
			$json = $this->requestParams['jsoncallback'] . '(' . Zend_Json::encode($eventArray) . ')'; 
		else {
			// Otherwise return as a JSON array
			$json = Zend_Json::encode($eventArray);		
		}
		
		$this->getResponse()->setHeader('Content-Type','application/x-javascript')->appendBody($json);
		$this->_helper->viewRenderer->setNoRender();
		
	}


}
