from parallels.common import messages
import logging
import itertools
from xml.etree.ElementTree import ElementTree
from parallels.common.actions.base.common_action import CommonAction
from parallels.common.actions.utils.logging_properties import LoggingProperties
from parallels.common.target_panels import TargetPanels

logger = logging.getLogger(__name__)


class CleanupBackupXMLForPPA(CommonAction):
	def get_description(self):
		return "Cleanup backup XML for PPA"

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return messages.FAILED_CLEANUP_BACKUP_XML_FOR_PPA

	def get_logging_properties(self):
		"""Get how action should be logged to migration tools end-user

		:rtype: parallels.common.actions.utils.logging_properties.LoggingProperties
		"""
		return LoggingProperties(info_log=False)

	def run(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		if global_context.target_panel != TargetPanels.PPA:
			return

		plesk_server = global_context.conn.target.plesk_server

		if plesk_server.get_plesk_version() >= (12, 0):
			return

		for _, backup in global_context.migrator.iter_converted_backups():
			root_nodes = [backup.container.backup_info.getroot()]
			for indexed in backup.get_indexed():
				if isinstance(indexed.xml, ElementTree):
					root_nodes.append(indexed.xml.getroot())
				else:
					root_nodes.append(indexed.xml)

			for root_node in root_nodes:
				if 'dump-original-version' in root_node.attrib:
					root_node.attrib.pop('dump-original-version')
				dump_info_node = root_node.find('.//dump-info')
				if dump_info_node is not None:
					server_id_node = dump_info_node.find('server-id')
					if server_id_node is not None:
						dump_info_node.remove(server_id_node)

				for node in itertools.chain(
					root_node.findall('.//domain'),
					root_node.findall('.//client'),
					root_node.findall('.//dns-zone')
				):
					for attr in ('owner-name', 'vendor-login', 'sync-with-parent'):
						if attr in node.attrib:
							node.attrib.pop(attr)
