<?
require_once "interface.Address_Book.php";

class Address_Book_File implements Address_Book {
	const RS = "\n";
	const FS = "\t";

	private $fh;
	public function __construct($file) {
		@mkdir(dirname($file));
		$this->fh = fopen($file, "a+b");
		if (!$this->fh) {
			throw new Exception("Oooops, Problem mit $file");
		}
		flock($this->fh, LOCK_EX);
		$stat = fstat($this->fh);
		if ($stat['size'] == 0) {
			fputs($this->fh, join(self::FS, array("Hans Hanson", "0815", "hans@hanson.de"))
				. self::RS);
		}
		flock($this->fh, LOCK_SH);
		fseek($this->fh, 0, SEEK_SET);
	}

	public function get_all_entries() {
		$entries = array();
		fseek($this->fh, 0, SEEK_SET);
		while($line = stream_get_line($this->fh, 0, self::RS)) {
			if ($line === FALSE) break;
			$entries[] = explode(self::FS, $line);
		}
		return $entries;
	}

	public function add_entry($entry) {
		$fields = array('name', 'tel', 'mail');
		$new = array();
		foreach($fields as $key) {
			if (!isset($entry[$key])) return;
			$new[$key] = trim($entry[$key]);
			$new[$key] = preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]);
			if (empty($new[$key])) return;
		}

		flock($this->fh, LOCK_EX);
		fputs($this->fh, join(self::FS, $new) . self::RS);
		flock($this->fh, LOCK_UN);
	}

	public function search_entries($pattern) {
		$pattern = trim($pattern);
		if (empty($pattern)) return array();
		fseek($this->fh, 0, SEEK_SET);
		$pattern = preg_replace('|/|', '\/', $pattern);
		$entries = array();
		while ($line = stream_get_line($this->fh, 0, self::RS)) {
			if ($line === FALSE) break;
			if (!preg_match("/$pattern/i", $line)) continue;
			$entry = explode(self::FS, $line);
			$entries[] = array('name' => $entry[0],
					   'tel' => $entry[1],
					   'mail' => $entry[2]);
		}
		return $entries;
	}

	public function delete_entries($ids) { }
}

?>
