<?php

abstract class Atmail_Files_Adapter_Abstract {
	
	const TYPE_FILE = 1;
	const TYPE_DIR = 2;
	const TYPE_ALL = 3;
	
	protected $_account;
	protected $dbAdapter;
	
	public function __construct($account) {
		$this->_account = $account;
		$this->dbAdapter = Zend_Registry::get('dbAdapter');
	}
	
	abstract public function delete($path);
	
	abstract public function createDirectory($path);
	abstract public function createFile($path, $stream);
	
	abstract public function getFile($path); // returns stream
	abstract public function rename($oldPath, $newPath);

	abstract public function getFileInfo($path);
	abstract public function getFiles($path, $type = self::TYPE_ALL);
	
    public function createComment($path, Atmail_Files_Comment $fileComment) {
	
		$path = realpath( $this->getFullPath($path) );

		$this->dbAdapter->INSERT("FileComments", array(
													'Comment' => $fileComment->comment,
													'FileID' => $this->getFileID( $path ),
													'Account' => $this->_account
												));

		return $lastId = $this->dbAdapter->lastInsertId();
		
	}

	public function getFileID($path)
	{
		// To reduce the confiction of one md5, here use double md5
		return md5($path) . md5( basename($path) );
	}
	
	public function deleteComment($path) {

		$path = realpath( $this->getFullPath($path) );
		
		return $this->dbAdapter->delete("FileComments", $this->dbAdapter->quoteInto("Account = ?", $this->_account) . ' AND ' . $this->dbAdapter->quoteInto("FileID = ?", $this->getFileID($path)));
		
	}

	public function deleteCommentById($path, $commentId) {

		$path = realpath( $this->getFullPath($path) );

		return $this->dbAdapter->delete("FileComments", $this->dbAdapter->quoteInto("Account = ?", $this->_account) 
				. ' AND ' . $this->dbAdapter->quoteInto("FileID = ?", $this->getFileID($path))
				. ' AND ' . $this->dbAdapter->quoteInto("id = ?", $commentId) );
	}

	public function updateComment($oldPath, $newPath) {
		
		$newpath = realpath( $this->getFullPath($newPath) );

		return $this->dbAdapter->update("FileComments", array('FileID' => $this->getFileID($newPath)), $this->dbAdapter->quoteInto('FileID = ?', $this->getFileID($oldPath)) . ' AND ' . $this->dbAdapter->quoteInto('Account = ?', $this->_account));
				
	}
	
	public function getComments($path) {
		
		// Returns an array of Atmail_Files_Comment
		return $this->dbAdapter->fetchAll("select *, unix_timestamp(DateAdded) as DateEpoch from FileComments where FileID=? and Account = ?", array( $this->getFileID(realpath($path)), $this->_account) );
		
	}
			
	
}


?>