<?php
//WARNING this is the quick mashup implimentation and does not make propper use of JSON as the data transport to the client (uses HTML inside JSON/AJAX calls)
//REFER to api/UnifyController for best practice implimentation.

class Mail_ServiceController extends Atmail_Controller_Action
{
	
	public function init()
	{
	
		$this->view->addHelperPath('library/Atmail/View/Helper/', 'Atmail_View_Helper');
	
	}

	public function preDispatch()
	{

		require_once 'library/jQuery/jQuery.php';
		require_once 'serviceproviderapi.php';
		
		if( $this->getRequest()->isXmlHttpRequest() || $this->getRequest()->isAjax )
		{
			$this->view->jsonIdsToRender = array();
			Zend_Registry::get('log')->info(__METHOD__ . ' isAJAX request');//show a hidden dialog box and include desired content
			$this->isAjax = true;
		}
		else
		{
			Zend_Registry::get('log')->info(__METHOD__ . ' normal HTML request');//show a hidden dialog box and include desired content
			$this->isAjax = false;
		}

		// check if we have been authenticated... and redirect if not
		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', 'index', 'default');
			return;
		}
		else
		{
			$this->view->UserSettings = Zend_Registry::get('UserSettings');
			$this->view->requestParams = $this->_request->getParams();
			$this->view->setEncoding('UTF-8');
			$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
			$this->view->appBaseUrl = $this->_request->getBaseUrl() . (strpos($this->_request->getBaseUrl(),'index.php')?'':'/index.php');
			$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->view->requestParams['module']=='default'?'':DIRECTORY_SEPARATOR . $this->view->requestParams['module']);
			$this->view->thisActionURL = $this->view->moduleBaseUrl . '/' . $this->view->requestParams['controller'] . '/' . $this->view->requestParams['action'];
			$this->view->notices = array();
			$this->view->errors = array();
			$this->session = new Zend_Session_Namespace('defaultNamespace');
			$this->userData = Zend_Auth::getInstance()->getStorage()->read();
			$this->_globalConfig = Zend_Registry::get('config')->global;
		}
			
		// Next, init the serviceprovider object
		$this->serviceprovider = new serviceproviderapi( array('Account' => $this->userData['Account']) );
		
		// Load the temporary location of the cache ( add admin check )
		$this->tmpFolderBaseName = users::getTmpFolder();

		// Load a Zend_Cache object for data ( response times! )
		$this->frontendOptions = array(
		   'lifetime' => 4,
		   'automatic_serialization' => true
		);
		$this->cacheEnabled = false;
		$this->backendOptions = array('cache_dir' => $this->tmpFolderBaseName);
		
		
	}

	public function indexAction()
	{

	}
	
	public function listAction()
	{
		
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
	    
		$requiredParams = array('pid', 'folder'); //pid = providerid
		foreach( $requiredParams as $requiredParam )
			if( !array_key_exists($requiredParam, $requestParams ) )
				throw new Exception('Called without required param: ' . $requiredParam);
		
		$this->view->query = $requestParams['query'];
		$this->view->pid = $requestParams['pid'];
		if( array_key_exists('folder', $requestParams) )
        	$this->view->folder = urldecode($requestParams['folder']);
		else
			$this->view->folder = 'irrelevant';
		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );
//Zend_Registry::get('log')->debug( "\n" . print_r($this->view->serviceAccount, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$this->view->serviceAccount \n");
		
		
		$providerLower = strtolower($this->view->serviceAccount['Provider']);
		if( $providerLower == 'facebook' )
			$providerLower = 'fb';
		$this->view->providerLower = $providerLower;
		//One provider for now intil full plugin framework implimented
		$providers = array( $this->view->serviceAccount );
		$this->view->providers = new Atmail_Providers( $providers );
		$this->view->myName = $this->view->providers->getMyName( array('pid' => $requestParams['pid']) );
		$this->view->myId = $this->view->providers->getMyId( array('pid' => $requestParams['pid']) );
		$this->view->myProfileImageUrl = $this->view->providers->getMyProfileImageUrl( array('pid' => $requestParams['pid']) );
		
		// Load a Zend_Cache object for data ( response times! )
		$frontendOptions = array(
			//'lifetime' => 600,
			'lifetime' => 4,
			'automatic_serialization' => true
		);
		
		$backendOptions = array('cache_dir' => $this->tmpFolderBaseName);
		
		// Setup the cache object
		$cache = Zend_Cache::factory('Output', 'File', $frontendOptions, $backendOptions);

		// Base the MD5 on the content of the image
		$cacheName = md5($requestParams['pid'] . $requestParams['folder']);

		if( !$this->cacheEnabled || !$this->view->summary = $cache->load($cacheName)) {
			$this->view->summary = $this->view->providers->getSummary( array('pid' => $requestParams['pid'], 'folder' => $this->view->folder));

			$cache->save($this->view->summary, $cacheName);

		}
		
		$this->_helper->viewRenderer->setNoRender();	
		$this->view->jsonIdsToRender["messageList"] = 'service/list'.$providerLower.'summary.phtml';
		$this->view->jsonIdsToRender["mail_info"] = 'service/view'.$providerLower.'summary.phtml';
		
		$this->render('global/jsonresponse', null, true);
		
	}

	public function viewAction()
	{
		
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		$requiredParams = array('pid', 'mid'); //pid = providerid, uid = unique id of message
		foreach( $requiredParams as $requiredParam )
			if( !array_key_exists($requiredParam, $requestParams ) )
				throw new Exception('Called without required param: ' . $requiredParam);

		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );
		$this->view->pid = $requestParams['pid'];
		if( array_key_exists('folder', $requestParams) )
        	$this->view->folder = urldecode($requestParams['folder']);
		else
			$this->view->folder = 'irrelevant';
		//One provider for now intil full plugin framework implimented
		$providers = array( $this->view->serviceAccount );
		$this->view->providers = new Atmail_Providers( $providers );

		// Setup the cache object
		$cache = Zend_Cache::factory('Output', 'File', $this->frontendOptions, $this->backendOptions);

		// Base the MD5 on the content of the image
		$cacheName = md5($requestParams['pid'] . $requestParams['mid']);

		if( !$this->cacheEnabled || !$this->view->thread = $cache->load($cacheName)) {

			$this->view->thread = $this->view->providers->getThread( array('pid'=>$requestParams['pid'], 'folder' => urldecode($requestParams['folder']), 'mid'=>$requestParams['mid']) );
			$cache->save($this->view->thread, $cacheName);

		}

		$providerLower = strtolower($this->view->serviceAccount['Provider']);
		if( $providerLower == 'facebook' )
			$providerLower = 'fb';

		$this->view->jsonIdsToRender["mail_info"] = 'service/view'.$providerLower.'summary.phtml';

		$this->_helper->viewRenderer->setNoRender();	
		$this->render('global/jsonresponse', null, true);

	}
	
	public function commentAction()
	{
		//this method should be moved into the provider implimentation bcause they are specific to Facebook - would be called throguh __call
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		$requiredParams = array('pid', 'oid', 'comment'); //pid = providerid, mid = unique id of message
		foreach( $requiredParams as $requiredParam )
			if( !array_key_exists($requiredParam, $requestParams ) )
				throw new Exception( __CLASS__ . "::" . __METHOD__ . "#" . __LINE__ . ' Called without required param: ' . $requiredParam);
		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );

		//One provider for now intil full plugin framework implimented
		$providers = array( $this->view->serviceAccount );
		$this->view->providers = new Atmail_Providers( $providers );
		
		$result = $this->view->providers->comment( array('pid' => $requestParams['pid'], 'oid' => $requestParams['oid'], 'comment' => $requestParams['comment']) );
//Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
		$this->_helper->viewRenderer->setNoRender();	
		echo Zend_Json::encode($result);
		
		//$result = $facebook->api( '/me/feed/', 'post',  array('access_token' => $this->access_token, 'message' => 'Playing around with FB Graph..') );
		

	}
	
	public function likeAction()
	{

		//this method should be moved into the provider implimentation bcause they are specific to Facebook - would be called throguh __call
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		$requiredParams = array('pid', 'oid'); //pid = providerid, mid = unique id of message
		foreach( $requiredParams as $requiredParam )
			if( !array_key_exists($requiredParam, $requestParams ) )
				throw new Exception('Called without required param: ' . $requiredParam);
		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );

		//One provider for now intil full plugin framework implimented
		$providers = array( $this->view->serviceAccount );
		$this->view->providers = new Atmail_Providers( $providers );

		$result = $this->view->providers->like( array('pid' => $requestParams['pid'], 'oid' => $requestParams['oid']) );
//Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
		$this->_helper->viewRenderer->setNoRender();	
		echo Zend_Json::encode( 'success' );

	}
	
	public function postAction()
	{
		
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		$requiredParams = array('pid', 'oid', 'message'); //pid = providerid, mid = unique id of message
		foreach( $requiredParams as $requiredParam )
			if( !array_key_exists($requiredParam, $requestParams ) )
				throw new Exception('Called without required param: ' . $requiredParam);
		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );

		//One provider for now intil full plugin framework implimented
		$providers = array( $this->view->serviceAccount );
		$this->view->providers = new Atmail_Providers( $providers );
		$requestParams['folder'] = "statuses/update";
		$result = $this->view->providers->post( array('pid' => $requestParams['pid'], 'url' => $requestParams['folder'], 'message' => $requestParams['message']) );
//Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
		$this->_helper->viewRenderer->setNoRender();	
		echo Zend_Json::encode( 'success' );
		
	}
	
	public function getAction()
	{
		
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		$folder = urldecode($requestParams['folder']);
		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );

		//One provider for now intil full plugin framework implimented
		$providers = array( $this->view->serviceAccount );
		$this->view->providers = new Atmail_Providers( $providers );
		$result = $this->view->providers->get( array('pid' => $requestParams['pid'], 'folder' => $folder) );
		$this->_helper->viewRenderer->setNoRender();	
		
		echo Zend_Json::encode($result);
		
	}
	
	public function deleteAction()
	{
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		
		//TODO
		$this->_helper->viewRenderer->setNoRender();	
		$this->render('global/jsonresponse', null, true);
		
	}
	
	// Poll the server for new SMS messages and popup in the DIV
	public function pollAction()
	{

		
		//TODO
		$this->_helper->viewRenderer->setNoRender();	
		
		
	}
	
	public function searchAction()
	{
		
	}
	
	public function newAction()
	{
		
		$requestParams = $this->getRequest()->getParams();
//Zend_Registry::get('log')->debug( "\n" . print_r($requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$requestParams \n");
		$this->view->serviceAccount = $this->serviceprovider->getAccount( $requestParams['pid'] );
        $providerLower = strtolower($this->view->serviceAccount['Provider']);
		if( $providerLower == 'facebook' )
			$providerLower = 'fb';
		
		if( empty($providerLower) )
			$providerLower = 'fb';
		
		$this->view->pid = $requestParams['pid'];
		$this->view->postType = 'default';
		$this->view->jsonIdsToRender["socialThreads"] = 'service/new'.$providerLower.'post.phtml';
		$this->_helper->viewRenderer->setNoRender();
		
		$this->render('global/jsonresponse', null, true);
		
	}
	
	public function reloadtemplateAction() //TODO: secure or remove after template dev done
	{
		
		$requestParams = $this->getRequest()->getParams();
		$template = $requestParams['template'];
		if( empty($template) )
			throw new Exception("template not specified");
		//$this->view->jsonIdsToRender = array( $template => 'service/'.$template.'.phtml');
		
		$this->_helper->viewRenderer->setNoRender();
		//$this->render('global/jsonresponse', null, true);
		echo $this->view->partial('service/'.$template.".phtml", null, array("siteBaseUrl" => $this->view->siteBaseUrl, "moduleBaseUrl" => $this->view->moduleBaseUrl));

	}
	public function updateAction()
	{
		$requestParams = $this->getRequest()->getParams();
	
		users::setUserSipNumber($this->userData['Account'], $requestParams['number']);
		jQuery('#header .YesNumber')->text($requestParams['number']);
				
		$this->render('global/jsonresponse', null, true);
	}
	
	public function sendcallrequestAction()
	{
		$fbConfigFilename = realpath(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/fb/config.ini';
		$config = parse_ini_file( $fbConfigFilename );
		
		if($config === false)
		{
			throw new Exception("Facebook configuration missing.");
		}
		
		$requestParams = $this->getRequest()->getParams();
		
		$this->_helper->viewRenderer->setNoRender();
		$serviceAccounts = $this->serviceprovider->listAccounts();
		
		$SIPAccount = null;
		$facebookAccount = null;
		foreach( $serviceAccounts as $serviceAccount )
		{
			if( $serviceAccount['Type'] == "SIP" )
				$SIPAccount = $serviceAccount;
			if( $serviceAccount['Provider'] == "Facebook" )
				$facebookAccount = $serviceAccount;
		}
		
		if( !array_key_exists('toDisplayName', $requestParams) ) 
			$requestParams['toDisplayName'] = $requestParams['to'];

		$requestParams['fromDisplayName'] = $this->userData['emailName'];
		$requestParams['fromEmailName'] = $this->userData['Account'];

		if( $SIPAccount == null || $facebookAccount == null )
			throw new Exception(__METHOD__ . ' #' . __LINE__ . " unable to get SIP account and FB account to compose call request.");
		
		//TODO: generate callback token to be used instead for callback authentication
		$fbProvider = new Atmail_Providers( array($facebookAccount) );
		//$message = 'I want to call you on Atmail Webphone http://apps.facebook.com/atmailcall/getcall.php?id='.$requestParams['to'] . '&from=' . $SIPAccount['PhoneNumber'];
		$token = md5( "to" . $requestParams['to'] . 'from' . $SIPAccount['PhoneNumber'] . microtime(true) . rand(100000,999999) );
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$q = "INSERT INTO `callbacks` (`Account`, `from`, `to`, `toDisplayName`, `token`, `expires`, `logDate`) VALUES ('" . $this->userData['Account'] . "', '" . $SIPAccount['PhoneNumber'] . "', '" . $requestParams['to'] . "', '" . $requestParams['toDisplayName'] . "', '" . $token . "', '" . (time()+300) . "', NOW() )";
		
		$dbAdapter->query($q);
		$config = Atmail_Provider_SocialNetwork_Facebook::parseConfig($config, $requestParams);

		$message = $config['ChatMessage'] . ' apps.facebook.com/' . $config['fbappid'] . '/?token=' . $token;
		$result = $fbProvider->sendChatMessage( array('pid' => $facebookAccount['id'], 'to' => $requestParams['to'], 'message' => $message) );
		echo Zend_Json::encode($result);
		
		
	}
	
	public function __call( $name, $arguments)
	{
		
//Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": Calling providers method $name with: \n" . print_r($arguments, true) );
		//pass call direct to providers expecting json response
		
	}
	
}
