<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*
* Author: Atmail
* Used for maintaining server logon information in AbookServers
*/

require_once 'Atmail/Abook/AbookDefines.php';

class Atmail_Abook_Servers
{
	protected $Account;
	private $_listCurrent = false;

	public function __construct( array $args = array() )
	{
		$this->dbAdapter = Zend_Registry::get('dbAdapter');
		$this->Account = $args['Account'];
	}
	
	public function GetServers($account = null)
	{
		if( $account == null )
		{
			$account = $this->Account;
		}
		
		if( isset($this->_listCurrent[$account]) )
		{
			return $this->_listCurrent[$account];
		}
		
		$q = 'SELECT * FROM AbookServers WHERE Account = ' . $this->dbAdapter->quote($account);
		$servers = $this->dbAdapter->fetchAll($q);

		foreach( $servers as &$server )
		{
			$server['id'] = ABOOK_SERVER_GROUP_TAG . $server['id'];	
		}
		
		$this->_listCurrent[$account] = $servers;
		return $servers;
	}
	
	public function AddServer($protocol, $url_protocol, $server, $port, $username, $password, $url)
	{

		$account = $this->Account;
		$args = array('Account' => $account, 'username' => $username, 'password' => $password, 'server' => $server, 'port' => $port, 'url' => $url, 'protocol' => $protocol);
        
		require_once('Atmail/Abook/Abook.php');
		$newAbookStore = new Atmail_Abook($args);
		
		if( !$newAbookStore->TestServer() )
		{
			return false;
		}
		else
		{
			$this->dbAdapter->insert("AbookServers", $args);
			$id = $this->dbAdapter->lastInsertId();
			$id = ABOOK_SERVER_GROUP_TAG . $id;
		}
        $this->_listCurrent[$account][] = $args;

        return $id;
	}
		
	public function DeleteServer($id = '')
	{

		if( $id == '')
			return FALSE;

		$account = $this->Account;
		
		$id = str_replace(ABOOK_SERVER_GROUP_TAG, '', $id);	
		
		$this->dbAdapter->Delete('AbookServers', 'Account = ' . $this->dbAdapter->quote($account) . ' and id = ' . $this->dbAdapter->quote($id));

		if(!isset($this->_listCurrent) || !isset($this->_listCurrent[$account]))
		{
			$this->GetServers($account);		
		}
		
		foreach( $this->_listCurrent[$account] as $k => $v )
		{
			if( $v['id'] == $id )
			{
				unset($this->_listCurrent[$account][$k]);
			}
		}
		
		return TRUE;
	}
}

