<?php
class Api_FolderController extends Atmail_Rest_Controller
{
	public function indexAction() {

        $params = $this->getRequest()->getParams();

        $acct = $params['acct'];
        $folder = $params['folder'];

        if (!isset($acct))
        {
            $acct = 0;
        }

        if ($acct > 0)
        {
            $inbox = new inbox();
            $iMapFolders = $inbox->getImapFolders($acct);

            $this->renderJson($iMapFolders);
            return;
        }


		$foldersObject = $this->AtmailMailStorageMain->getFolders();
		$folders = new RecursiveIteratorIterator($foldersObject, RecursiveIteratorIterator::SELF_FIRST);
		$arr = array();
		$key = "";

		foreach($folders as $c => $v) {
			$gname = $v->getGlobalName();

			$arr[] = array(
				'localName' => $v->getLocalName(),
				'globalName' => $gname,
				'selectable' => $v->isSelectable(),
				'isMainFolder' => in_array($v->getLocalName(), array('INBOX','Drafts','Sent','Spam','Trash'))? 1 : 0,
				'hasChildren' => $folders->haschildren(),
				'id' => $this->_createId( $gname )
			);

			if($folders->hasChildren()) {
				$folders->getChildren();
			}
		}
		
		$this->renderJson($arr);
	}

    public function getAction() {
    	$params = $this->getRequest()->getParams();
    	$this->renderJson($params);
    }
	

	public function putAction() {
		try{

			$payload   = $this->getPayload();
			$dlimiter  = $this->AtmailMailStorageMain->getFolderDelimiterDefault();
			$new_name  = $this->AtmailMailStorageMain->encodeUTF7( $payload->newName );
			$local     = $this->AtmailMailStorageMain->encodeUTF7( $payload->localName );
			$global    = $this->AtmailMailStorageMain->encodeUTF7( $payload->globalName );
			$dlimPos   = strrpos($global,$dlimiter);
			$newGlobal = null;

			if($dlimPos === false){
				$newGlobal = $new_name;
			} else {
				$newGlobal = substr($global, 0, $dlimPos) . "{$dlimiter}{$new_name}";
			}

			$newGlobal = $this->AtmailMailStorageMain->renameFolder($global, $newGlobal);
			$this->getResponse()->setHttpResponseCode( self::SUCCESS );

			$payload = array();
			$payload['globalName'] = $this->AtmailMailStorageMain->decodeUTF7( $newGlobal );
			$payload['localName'] = array_pop( explode($dlimiter,$payload['globalName']) );

		} catch(Atmail_Mail_Exception $e) {
			$this->getResponse()->setHttpResponseCode( self::NOTMODIFIED );

			// This will not return unless the response code above is changed to 200
			$payload->error = $e;
		}
		$this->renderJson($payload);
	}

	public function postAction(){

		$payload = $this->getPayload();

		$log = Zend_Registry::get('log');

		$dlimiter  = $this->AtmailMailStorageMain->getFolderDelimiterDefault();

		if( !$payload->globalName )
		{
			throw new Atmail_Mail_Exception('Compulsory argument, < globalName >, not present');
		}

		$currentFolder = $this->AtmailMailStorageMain->getCurrentFolder();

		//if main folder force to root folder (physically in INBOX. (main namespace root), but logically (according to UI) appears as a root folder)
		//special ids for reserved folders
		$mainFoldernamesGlobal = array();
		$mainFoldernamesGlobal[] = $this->AtmailMailStorageMain->getMainFolderName();
		$mainFoldernamesGlobal[] = $this->AtmailMailStorageMain->getMainFolderName('Sent');
		$mainFoldernamesGlobal[] = $this->AtmailMailStorageMain->getMainFolderName('Trash');
		$mainFoldernamesGlobal[] = $this->AtmailMailStorageMain->getMainFolderName('Drafts');
		$mainFoldernamesGlobal[] = $this->AtmailMailStorageMain->getMainFolderName('Spam');

		if( in_array($currentFolder, $mainFoldernamesGlobal) || strpos($payload->globalName, $dlimiter)===false )
			$currentFolder = $this->AtmailMailStorageMain->getFolderNamespaceDefault();

		$folderNameNewAsOrigionallySuppliedFromJsEncoding = $payload->globalName;
		$folderNameNew = urldecode( $payload->globalName );
		$folderNameNewUrlencodedDouble = urlencode( urlencode( $folderNameNew ) );
		$folderNameNewUTF7 = $this->AtmailMailStorageMain->encodeUTF7( $folderNameNew );
        $folderNameGlobalOrigional = urlencode($folderNameNewAsOrigionallySuppliedFromJsEncoding);
			
		try
		{
			$folderNameGlobalUTF7 = $this->AtmailMailStorageMain->createFolder( $folderNameNewUTF7, $currentFolder );
			
			$payload = array();
			$payload['globalName'] = $this->AtmailMailStorageMain->decodeUTF7( $folderNameGlobalUTF7 );
			$payload['localName']  = array_pop( explode($dlimiter, $payload['globalName']) );
			$payload['id'] = $this->_createId( $payload['globalName'] );

			$this->getResponse()->setHttpResponseCode(self::SUCCESS);
			$this->renderJson($payload);

		}
		catch( Exception $e ) 
		{
			$this->getResponse()->setHttpResponseCode(self::NOTMODIFIED);			
		}
		
	}

	public function deleteAction() {
		try{
			$payload = $this->getRequest()->getParams();

			$preserveList = array();
			$preserveList[] = $this->AtmailMailStorageMain->getMainFolderName('Inbox');
			$preserveList[] = $this->AtmailMailStorageMain->getMainFolderName('Sent');
			$preserveList[] = $this->AtmailMailStorageMain->getMainFolderName('Trash');
			$preserveList[] = $this->AtmailMailStorageMain->getMainFolderName('Drafts');
			$preserveList[] = $this->AtmailMailStorageMain->getMainFolderName('Spam');

			$folderNameGlobalUTF7 = $this->AtmailMailStorageMain->encodeUTF7( $this->_decodeId( $payload['id'] ) );

			if( in_array($folderNameGlobalUTF7, $preserveList) )
			{
				throw new Atmail_Mail_Exception( $this->translate('Cannot remove a main folder') );
			}

			//TODO: only switch to root folder if not selected or sub folder.
			$rootFolderGlobalUTF7 = $this->AtmailMailStorageMain->getMainFolderName();
			
			$rootFolderGlobalUTF7UrlencodedDouble = urlencode( urlencode( $rootFolderGlobalUTF7 ) );
			$this->AtmailMailStorageMain->selectFolder( $rootFolderGlobalUTF7 ); //change to inbox first
			

			$listOfDeletedFolders = array();
			$folderObject = $this->AtmailMailStorageMain->getFolderObjectByName( $folderNameGlobalUTF7 );
			
			if( $folderObject == null )
			{
				// throw new Exception( $this->translate("Unable to remove folder. Folder not found [{$folderNameGlobalUTF7}]") );
				throw new Exception( utf8_encode("Unable to remove folder. Folder not found [{$folderNameGlobalUTF7}]"), 1011 );
			}

			$foldersRemoved = 0;
			foreach( new RecursiveIteratorIterator( $folderObject, RecursiveIteratorIterator::SELF_FIRST) as $object )
			{
				$this->_moveFolderContentsToTrash($object);			
				$this->AtmailMailStorageMain->selectFolder( $rootFolderGlobalUTF7 );			
				$listOfDeletedFolders[] = $object->getGlobalName();
				$this->AtmailMailStorageMain->removeFolder( $object->getGlobalName() );
				$foldersRemoved++;
				
			}
			
			//remove parent (for some reason ::SELF_FIRST is not including self)
			if( !in_array($folderNameGlobalUTF7, $listOfDeletedFolders) )
			{
				$this->_moveFolderContentsToTrash($folderObject);			
				$this->AtmailMailStorageMain->selectFolder( $rootFolderGlobalUTF7 );				
				$this->AtmailMailStorageMain->removeFolder( $folderNameGlobalUTF7 );
				$foldersRemoved++;
			}

		   	//call a cleanup on the head node that was deleted
			$folderNameGlobalUTF7UrlencodedDouble = urlencode( urlencode( $folderNameGlobalUTF7 ) );
			$this->getResponse()->setHttpResponseCode(self::SUCCESS);

		} catch(Exception $e) {
			$this->getResponse()->setHttpResponseCode(self::SUCCESS);
			// change httpResponseCode to self::SUCCESS to recieve $payload

			$payload['error'] = $e;
			$payload['id_decoded'] = $this->_decodeId($payload['id']);
			$this->renderJson($payload);
		}
	}

	private function _moveFolderContentsToTrash($folderObject)
	{
		$this->AtmailMailStorageMain->selectFolder($folderObject->getGlobalName());
		$messages = $this->AtmailMailStorageMain->getBasicHeaders();
				
		$messageUIDsToMove = array();				
		foreach($messages as $message)
		{
			$messageUIDsToMove[] = (int) $message['UID'];
		}

		if(count($messageUIDsToMove))
		{
			$this->AtmailMailStorageMain->moveMessage($messageUIDsToMove , $this->AtmailMailStorageMain->getMainFolderName('Trash'));
		}
	}

	private function _createId($globalName)
	{
		return urlencode( base64_encode($globalName) );
	}

	private function _decodeId($id)
	{
		return base64_decode( urldecode( urldecode($id) ) );
	}
}

?>