import logging

from parallels.plesk.client_subscription_converter import TargetPleskClientSubscriptionConverterAdapter
from parallels.ppa.source.plesk.migrator import Migrator as PleskMigrator
from parallels.core.migration_list import MigrationListData, SubscriptionMappingInfo, SubscriptionIPMapping
from parallels.shcm_web_sn.source.shcm_web_sn import SHCM_PLESK_VERSION
from parallels.shcm_web_sn.source.shcm_web_sn.source_server import SHCMMoveWebspacesSourceServer
from parallels.shcm_web_sn.source.shcm_web_sn.connections import SHCMMoveWebspacesWebSnSourceConnections
from parallels.shcm_web_sn.source.shcm_web_sn.global_context import SHCMMoveWebspacesGlobalMigrationContext
from parallels.ppa.utils import poa_utils
from parallels.core.utils.common import cached

logger = logging.getLogger(__name__)


class Migrator(PleskMigrator):
	def _load_connections_configuration(self):
		return SHCMMoveWebspacesWebSnSourceConnections(
			self.global_context, self._get_target_panel(), self._get_migrator_server()
		)

	def _create_global_context(self):
		return SHCMMoveWebspacesGlobalMigrationContext()

	def get_converter_adapter(self):
		"""
		:rtype: parallels.core.client_subscription_converter.ClientSubscriptionConverterAdapter
		"""
		return TargetPleskClientSubscriptionConverterAdapter()

	@cached
	def _get_source_node(self, node_id):
		return SHCMMoveWebspacesSourceServer(
			node_id, self._get_source_servers()[node_id],
			self._get_migrator_server(), SHCM_PLESK_VERSION, self.conn.mn_server,
			self.global_context.webspace_src_ctx.get_partition_path()
		)

	@cached
	def _get_source_web_node(self, subscription_name):
		ip = self.global_context.webspace_src_ctx.get_web_sn_ip()
		host_id = str(poa_utils.get_host_id_by_ip(self.conn.mn_server.poa_api(), ip))
		settings = self.source_servers['Source']._replace(id=host_id, ip=ip)

		return SHCMMoveWebspacesSourceServer(
			'Source', settings,
			self._get_migrator_server(), SHCM_PLESK_VERSION, self.conn.mn_server,
			self.global_context.webspace_src_ctx.get_partition_path()
		)

	def _read_migration_list(self, options, migration_list_optional=False):
		return MigrationListData(
			subscriptions_mapping={
				self.global_context.webspace_name: SubscriptionMappingInfo(
					plan=None,
					addon_plans=[],
					owner=None,
					# fixed IP addresses specified in move list
					ipv4=self.global_context.webspace_ipv4 or SubscriptionIPMapping.NONE,
					ipv6=self.global_context.webspace_ipv6 or SubscriptionIPMapping.NONE
				)
			},
			# We do not migrate resellers, customer and plans in SHM/SHCM move webspaces mode
			resellers={},
			customers_mapping={},
			plans={None: set()}
		)
