<?php

class Atmail_Migrate_Data_Email {

	private $_emailContent;
	private $_folder;
	private $_timestamp;
	private $_flags = array();
	private $_imapFlagMap = array(
		"SEEN"     => "S",
		"ANSWERED" => "R",
		"FLAGGED"  => "F"
	);
	
	
	public function setContent($email)
	{
		$this->_emailContent = $email;
	}
	
	public function setFolder($folder)
	{
		if (substr($folder, 0, 3) == "../" || empty($folder)) {
			return false;
		}
		
		if (substr($folder, 0, 1) != ".") {
		    $folder = str_replace(".", "\.", $folder);
			$folder = ".$folder";
		} else {
		    $folder = "." . str_replace(".", "\.", substr($folder, 1));
		}
		
		
		$this->_folder = $folder;
	}
	
	public function addFlag($flag)
	{
		$flag = strtoupper($flag);
		
		if (array_key_exists($flag, $this->_imapFlagMap) && !in_array($flag, $this->_flags)) {
			$this->_flags[] = $flag;
		}
	}

	public function setFlags(array $flags)
	{
		$this->_flags = array();
	
		foreach ($flags as $f) {
			$this->addFlag($f);
		}
	}
		
	public function setTimestamp($time)
	{
		$this->_timestamp = $time;
	}
	
	public function getFlags()
	{
		$flags = "";
		asort($this->_flags);
		foreach ($this->_flags as $f) {
			$flags .= $this->_imapFlagMap[$f];
		}
		
		return $flags;
	}
	
	public function getContent()
	{
		return $this->_emailContent;
	}
	
	public function getFolder()
	{
		return $this->_folder;
	}
	
	public function getTimestamp()
	{		
		if (!empty($this->_timestamp)) {
			return $this->_timestamp;
		}
		
		// Otherwise use the Date header to
		// get a timestamp
		
		if (preg_match("/^Date:(.+)$/", $this->_emailContent, $m)) {
			return strtotime($m[1]);
		}
		
		// Else just return current time
		return time();
	}

}
