<?php

abstract class Atmail_Rest_Controller extends Zend_Rest_Controller
{
	// REST HTTP 200s response codes
	const SUCCESS   = 200;
	const CREATED   = 201;
	const ACCEPTED  = 202;
	const NOCONTENT = 203;

	// 300s
	const NOTMODIFIED = 304;

	// 400s
	const BADREQUEST = 400;

	public function init(){

		$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();

		// Load all the params
		$this->requestParams = $this->getRequest()->getParams();

		// Use Cookie auth
		if( !Atmail_FormAuth::authenticated() )
		{
				return $this->_forward('timeout', 'mail', 'api', $this->requestParams);		
		}

		// Read from Zend-Auth
		$this->userData = Zend_Auth::getInstance()->getStorage()->read();
		$this->userData = Atmail_Password::processUser($this->userData);
			
		// Load the session
		$this->session = new Zend_Session_Namespace(ATMAIL_NAMESPACE);

		// 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');

		$this->log = Zend_Registry::get('log');
		
		// Used to determine the contact in the global addressbook
		$this->view->Account = $this->userData['Account'];

		// Load the mail class
		//handle folder change requests here (allowing change from all actions/events) so that correct cache can be loaded (correct folder)
		$this->_currentConfig = array();

		if( isset($this->view->requestParams['refresh']) )
		{
			$this->_currentConfig['cacheRefresh'] = $this->view->requestParams['refresh'];
		}

		if( isset($this->view->requestParams['selectFolder']) && $this->view->requestParams['selectFolder'] != 'undefined' )
		{
			$selectFolder = urldecode($this->view->requestParams['selectFolder']);
			$this->_currentConfig['folder'] = $selectFolder;
			if( isset($this->session->pageNumber) )
			{
				$this->session->pageNumber = 1;
			}
		}

		//set up mail store config to connect directly to correct folder if about to exec a move action
		if( isset($this->view->requestParams['fromFolder']) )
		{
			$fromFolder = urldecode($this->view->requestParams['fromFolder']);
			$this->_currentConfig['folder'] = $fromFolder;
			if( isset($this->session->pageNumber) )
			{
				$this->session->pageNumber = 1;
			}
		}

		$this->_mailStoreConfig = array_merge($this->_globalConfig, $this->userData, $this->_currentConfig, $this->view->UserSettings);
		if( isset($this->view->UserSettings['ThreadLimit']) )
		{

			$this->_mailStoreConfig['threadsLimitMonths'] = $this->view->UserSettings['ThreadLimit'];

		}

		//check if SSL enabled in UserSettings
		$this->_mailStoreConfig['ssl'] = ($this->_mailStoreConfig['UseSSL']=='1'?'SSL':'');

		$this->AtmailMailStorage = Atmail_Mail_Storage::getInstance($this->_mailStoreConfig);
		$this->AtmailMailStorageMain = &$this->AtmailMailStorage->getMailStore($this->_mailStoreConfig['namespaceName']);

		// Set thread support on/off from server response - Will be false if server does not support it
		$this->AtmailMailStorageMain->setThreadsEnabled( $this->view->UserSettings['ViewThreads'] );
	}

	protected function getPayload(){
		return json_decode($this->getRequest()->getRawBody());
	}

	protected function renderSuccess()
    {
        $this->renderJson(array(
            "result" => "success",
        ));
    }

    protected function renderFail(Atmail_Exception $e)
    {
        $this->renderJson(array(
            "result" => "failed",
            "error" => $e->getMessage(),
        ));
    }
	
	protected function doJsonResponse($arr, $needJSONP) {
		// If we are a JSONP request, wrap in a function
		if( $needJSONP )
			$json =  $this->requestParams['jsoncallback'] . '(' . Zend_Json::encode($arr) . ')';
		else {
			// Otherwise return as a JSON array
			$json = Zend_Json::encode($arr);
		}

		// Build the JSON packet and return
		$this->getResponse()->setHeader('Content-Type','application/x-javascript')->appendBody($json);
		$this->_helper->viewRenderer->setNoRender();
	}

	protected function renderJson($arr)
    {
        if( isset($this->requestParams['jsoncallback']) && $this->requestParams['jsoncallback'] && !empty($this->_globalConfig['jsonpAPI']) )
            $json =  $this->requestParams['jsoncallback'] . '(' . Zend_Json::encode($arr) . ')';
        else {
            // Otherwise return as a JSON array
            $json = Zend_Json::encode($arr);
        }

        $this->getResponse()->setHeader('Content-Type','application/x-javascript')->appendBody($json);
        $this->_helper->viewRenderer->setNoRender();
    }

    protected function translate($message){
    	// TODO
    	return $message;
    }
}
?>