import posixpath

from parallels.core.utils.paths.copy_web_content import CopyWebContentItem
from parallels.core.utils.paths import web_paths
from parallels.core.utils import plesk_utils
from parallels.plesk.source.plesk.actions.content.web.copy_unix_content import CopyUnixWebContentBase


class ConfixxCopyUnixWebContent(CopyUnixWebContentBase):
	def _list_files_to_copy(self, global_context, subscription):
		"""Make a list of source server directories to be transferred.

		Confixx content directories:
		Domain root directory of user webN:
			'/srv/www/htdocs/webN/html'
		Web statistics (webalizer):
			'/srv/www/htdocs/confixx/html/webalizer/webN' 
		Web statistics (awstats):
			'/srv/www/htdocs/confixx/awstats/webN' 
		Apache log files:
			'/srv/www/htdocs/webN/log'

		Return:
			A list of (source directory -> destination directory) mappings

		:type global_context: parallels.plesk.source.confixx.global_context.ConfixxGlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		:rtype: list[parallels.core.utils.paths.copy_web_content.CopyWebContentItem]
		"""
		vhosts_dir = global_context.confixx_configuration.get_vhosts_dir()
		source_vhost_name = subscription.raw_dump.owner_login
		tocopy = [
			CopyWebContentItem(
				source_path=web_paths.AbsolutePath(posixpath.join(vhosts_dir, source_vhost_name, 'html')),
				target_path=web_paths.WebspaceDocumentRoot(subscription.converted_dump),
			),
			CopyWebContentItem(
				source_path=web_paths.AbsolutePath(posixpath.join(vhosts_dir, source_vhost_name, "log")),
				target_path=web_paths.WebspaceLogs(subscription.converted_dump),
				skip_if_source_not_exists=True
			),
		]

		for site in subscription.raw_dump.iter_sites():
			site_vhost_name = plesk_utils.convert_wildcard_to_path(
				site.name.encode('idna')
			)
			
			# site logs
			tocopy.extend([
				CopyWebContentItem(
					source_path=web_paths.AbsolutePath(posixpath.join(vhosts_dir, site_vhost_name, 'log')),
					target_path=web_paths.SiteLogs(subscription.converted_dump, site),
					skip_if_source_not_exists=True
				),
			])

		return tocopy
