<?php
/**
 * User: james
 * Date: 30/05/12
 * Time: 10:02 AM
 */

class Atmail_Controller_Base extends Atmail_Controller_Action
{
	public function renderJson($arr)
	{
		$this->requestParams = $this->_request->getParams();

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

	public function renderSuccess($extraInfo = array())
	{
        $arr = array_merge($extraInfo, array(
            "result" => "success",
        ));

		$this->renderJson($arr);
	}

	public function renderFail(Atmail_Exception $e)
	{
		$this->renderJson(array(
			"result" => "failed",
			"error" => $e->getMessage(),
		));
	}

	public function doJsonResponse($arr, $needJSONP)
	{
		$this->requestParams = $this->_request->getParams();

		// 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();
	}
}
