import posixpath
from parallels.core.content.mail.rsync import SourceMailDirectory
from parallels.core.utils.paths.mail_paths import MailboxDirectory
from parallels.core.content.mail.rsync import CopyMailRsync


class CpanelCopyMailRsync(CopyMailRsync):
	def _get_target_path(self, target_server, target_location, domain_name):
		return posixpath.join(
				target_server.mail_dir, domain_name,
				target_location.mailbox_name, 'Maildir')


class CpanelSourceMailDirectory(SourceMailDirectory):
	"""Provide paths to directories with mail on cPanel server."""

	def prepare(self):
		source_server = self.subscription.mail_source_server
		result = []
		for mailbox in self.domain.iter_mailboxes():
			source_directory = self._get_source_mailbox_directory(
					source_server, mailbox)
			if source_directory is not None:
				target_directory = MailboxDirectory(mailbox.name.lower())
				result.append((source_directory, target_directory))
		return result

	def _get_source_mailbox_directory(self, server, mailbox):
		"""Return absolute path to mail directory.
		
		cPanel 11 domain has one default mail account with a Maildir +
		one Maildir per regular mail user. cPanel stores regular user maildirs
		inside default account's maildir.
		"""
		sysuser_name = self._get_sysuser_name(self.subscription)
		if mailbox.name == sysuser_name:
			# System (default) user mail directory
			return '/home/{client}/mail'.format(client=sysuser_name)
		else:
			return '/home/{client}/mail/{domain}/{mailname}'.format(
				client=sysuser_name, mailname=mailbox.name,
				domain=mailbox.domain_name)

	def get_excluded_files(self):
		"""Exclude domain name directory, which is a root for user Maildirs."""
		return [self.domain.name]

	def _get_sysuser_name(self, subscription):
		domain_xml = subscription.raw_dump.node
		sysuser_xml = domain_xml.findall('phosting/preferences/sysuser').pop()
		return sysuser_xml.attrib['name']
