from Globals import InitializeClass, DTMLFile
from Products.MailHost import MailHost
from AccessControl import ClassSecurityInfo
from AccessControl.Permissions import view_management_screens, change_configuration
import string, re

bad_path_chars_in=re.compile('[^a-zA-Z0-9-_~\,\. \/]').search



manage_addFakeMailHostForm=DTMLFile('www/addFakeMailHost_form', globals())
def manage_addFakeMailHost(dispatcher, id, title='', folderPath='', REQUEST=None) :
	' Add Fake mail Host'
	parent = dispatcher.Destination()
	fmh = FakeMailHost(id, folderPath, title='title' )
	parent._setObject(id, fmh)
	if REQUEST is not None:
		REQUEST['RESPONSE'].redirect(parent.absolute_url()+'/manage_main')


class FakeMailHost(MailHost.MailHost) :
	""" Fake Mail Host """
	
	meta_type = 'Fake Mail Host'
	manage_main = DTMLFile('www/manageFakeMailHost', globals())
	manage_main._setName('manage_main')
	smtp_host = ''
    
	security = ClassSecurityInfo()
	
	def __init__(self, id, folderPath, title='', ) :
		self.id = id
		self.title = title
		self.setContainerPath(path=folderPath)
		
	
	def _send(self, mfrom, mto, messageText, immediate=False) :
		""" Create a document based on message inside base folder """
		folder = self._getMailContainer()
		id = str(len(folder._objects))
		folder.manage_addProduct['OFSP'].manage_addFile(id, file='')
		file = getattr(folder, id)
		file.update_data(messageText, 'text/plain')

	security.declareProtected(change_configuration, 'manage_makeChanges' )
	def manage_makeChanges(self,title,folderPath, REQUEST=None):
		'make the changes'
		
		title=str(title)
		self.title=title
		self.setContainerPath(folderPath)
		
		if REQUEST is not None:
			msg = 'Fake Mail Host %s updated' % self.id
			return self.manage_main( self
									, REQUEST
									, manage_tabs_message=msg
									)
	
	security.declareProtected(view_management_screens, 'getFolderPath')
	def getFolderPath(self) :
		return '/'.join(self._folderPath)
		
	
	def _getMailContainer(self) :
		return self.unrestrictedTraverse(self._folderPath)
	
	security.declarePrivate('setContainerPath')
	def setContainerPath(self, path=None):
		if not path:
		    self._folderPath = []
		elif type(path) is type(''):
			if bad_path_chars_in(path):
				raise ValueError, (
				    'Path contains invalid 	characters in a Zope '
				    'object path'
				    )
			self._folderPath = string.split(path, '/')
		elif type(path) in (type([]), type(())):
			self._folderPath = list(path) # sequence
		else:
			raise ValueError, ('Bad path value %s' % path)
		
InitializeClass(FakeMailHost)