<?php
/**
 * @category 	Atmail
 * @package 	Models
 * @subpackage	Archive Vault API
 * @copyright 	Copyright (c) 2009-2011 ATMAIL. All rights reserved
 * @license 	See http://atmail.com/license.php for license agreement
 * @author		Allan Wrethman allan@staff.atmail.com
 * @author		Atmail (http://atmail.com)
 */
 
class archiveVaultAPIClient
{	
	
	private $_session;
	private $_config;
	private $_client;
	private $_baseMethodPath;
	private $_apiKeyPostpend;
		
	public function __construct( $config = null )
	{

		if( $config == null )
		{
			
			throw new Exception('Missing config arguments');
			
		}
		
		$this->_config = $config;
		
		$requiredConfigArgs = array('serverURI', 'basePath');
		foreach( $requiredConfigArgs as $required )
		{
			
			if( !array_key_exists( $required, $this->_config) )
			{
				
				throw new Exception('Missing config argument ' . $required);
				
			}
		
		}
		if( !array_key_exists( 'apiKey', $this->_config) && !(array_key_exists('username', $this->_config) && array_key_exists('password', $this->_config)) )
		{
			
			throw new Exception('Missing credential arguments, apiKey, or api username and password');
			
		}
		$this->_apiKeyPostpend = '';
		if( array_key_exists('username', $this->_config) && array_key_exists('password', $this->_config) )
		{
			Zend_Rest_Client::getHttpClient()->setAuth($this->_config['username'], $this->_config['password']);
			
		}
		else if( array_key_exists( 'apiKey', $this->_config) )
		{
			
			$this->_apiKeyPostpend = '/apiKey/' . $this->_config['apiKey'];
			
		}
		$this->_client = new Zend_Rest_Client( $this->_config['serverURI'] ); 
		$this->_baseMethodPath = $this->_config['basePath'] . 'index.php/api/users/';
	}
	
	public static function splitUrl( $URL )
	{
		
		//cleanup url and replace supplied
		$apiURLMainParts = explode('://', $URL);
		
		if( count($apiURLMainParts) == 1 )
		{
			
			array_unshift($apiURLMainParts,'http');
			
		}
		$apiURLOtherParts = explode('/', trim($apiURLMainParts[1], '/\\') );
		$serverURI = $apiURLMainParts[0] . '://' . array_shift($apiURLOtherParts);
        if (!empty($apiURLOtherParts)) {
            $basePath = '/' . implode('/', $apiURLOtherParts) . '/';      
		} else {
            $basePath = '/';
        }
        
		return array( 'serverURI' => $serverURI, 'basePath' => $basePath, 'url' => $serverURI . $basePath);
		
	}
	
	public function validateSettings()
	{
		
		$method = 'authenticate';
		
		$fullMethodURL = $this->_baseMethodPath . $method . $this->_apiKeyPostpend;
		
		$headerCall = @get_headers($this->_config['serverURI'] . $fullMethodURL);
		
		//Zend_Registry::get('log')->debug( "\n" . print_r($this->_config['serverURI'] . $fullMethodURL, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": fullMethodURL \n");
		//Zend_Registry::get('log')->debug( "\n" . print_r($headerCall, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$headerCall \n");
		
		if( $headerCall == false || strpos($headerCall[0],'404') !== false || stripos($headerCall[0],'Not Found') !== false)
		{
			
			return self::error('API not found at specified URL');
		
		}             

		try 
		{
			
			$result = @$this->_client->get($fullMethodURL);
		
			if( isset($result->authenticate->status) && $result->authenticate->status == 'success' )
			{

				return array( 'response' => array('message' => 'API Service appears to be online and API Key validated successfully'), 'status' => 'success');
			
			}
			else
			{
			
				return self::error($result->authenticate->response->message);
			
			}
			
		}
		catch( Exception $e ) 
		{

			$message = $e->getMessage();
			if( strpos($message, 'No route to host') !== false || strpos($message, 'Unable to Connect') !== false )
			{
				
				$message = 'Unable to connect to host.';
				
			}
			return self::error('Could not connect. ' . $message);
			
		}
	
		
	}
	
	public static function error($message)
	{

		return array( 'response' => array('message' => $message), 'status' => 'failed' );

	}
	
	

	
/**
 * ArchiveVault User API calls
*/
	public function authenticate() 
	{
		
		//Zend_Registry::get('log')->debug( "\n" . print_r($this->_baseMethodPath . 'authenticate' . $this->_apiKeyPostpend, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": URL \n");
		
		$result = $this->_client->get( $this->_baseMethodPath . 'authenticate' . $this->_apiKeyPostpend );
		//$result = $this->client->post($method, $args);
		return array('response' => array('message' => (string)$result->response->message), 'status' => (string)$result->status);
		
	}
	
	/*
	public function userexists( $username ) 
	{
		
		$result = $this->_client->get( $this->_baseMethodPath . 'userexists/username/' . $username . $this->_apiKeyPostpend );
		return array('response' => (string)$result->response->message, 'status' => (string)$result->status);
		
	}
	*/
	
	public function usercreate( $args )
	{
		
		//Zend_Registry::get('log')->debug( "\n" . print_r($args, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$args \n");
		//Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . $this->_baseMethodPath . 'create' . $this->_apiKeyPostpend);
		
		$result = $this->_client->post( $this->_baseMethodPath . 'create' . $this->_apiKeyPostpend, $args );
		//Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
		
		return array('response' => array('message' => (string)$result->usercreate->response->message), 'status' => (string)$result->usercreate->status);
		
	}
	
	public function userupdate( $args )
	{
		
		//Zend_Registry::get('log')->debug( "\n" . print_r($args, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$args \n");
		//Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": " . $this->_baseMethodPath . 'update' . $this->_apiKeyPostpend);
		
		$result = $this->_client->post( $this->_baseMethodPath . 'update' . $this->_apiKeyPostpend, $args );
		//Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
		
		return array('response' => array('message' => (string)$result->userupdate->response->message), 'status' => (string)$result->userupdate->status);
		
	}
	
	public function userdelete( $username )
	{
		
		//Zend_Registry::get('log')->debug( "\n" . print_r($username, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$username \n");
		
		$result = $this->_client->get( $this->_baseMethodPath . 'delete/username/' . $username . $this->_apiKeyPostpend );
		//Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
		return array('response' => array('message' => (string)$result->userdelete->response->message), 'status' => (string)$result->userdelete->status);
		
	}
	
}
