import logging

from parallels.core.migrator import SubscriptionTargetServices
from parallels.source.plesk.migrator import Migrator as PleskMigrator
from parallels.source.shm_web_sn.connections import PPAMoveWebspacesWebSnSourceConnections
from parallels.source.shm_web_sn.importer import PPAMoveWebspacesImporter
from parallels.source.shm_web_sn.source_server import PPAMoveWebspacesSourceServer
from parallels.source.shm_web_sn.workflow import PPAMoveWebspacesWorkflow
from parallels.source.shm_web_sn.global_context import PPAMoveWebspacesGlobalMigrationContext
from parallels.core.migration_list import MigrationListData, SubscriptionMappingInfo, SubscriptionIPMapping
from parallels.api.plesk.operator.subscription import Ips
from parallels.target.plesk.converter.converter import PleskConverter
from parallels.target.shm_web_sn.panel import PPAMoveWebspacesTargetPanel
from parallels.core.utils.common import cached

logger = logging.getLogger(__name__)


class Migrator(PleskMigrator):
	def _load_connections_configuration(self):
		return PPAMoveWebspacesWebSnSourceConnections(
			self.config, self._get_target_panel(), self._get_migrator_server()
		)

	def _create_workflow(self):
		return PPAMoveWebspacesWorkflow()

	def _create_global_context(self):
		return PPAMoveWebspacesGlobalMigrationContext()

	@cached
	def _get_target_panel(self):
		return PPAMoveWebspacesTargetPanel()

	def _get_converter_class(self):
		return PleskConverter

	def _get_importer(self, safe):
		return PPAMoveWebspacesImporter(self._get_target_panel_api(), self.conn.target, safe)

	@cached
	def _get_source_node(self, node_id):
		return PPAMoveWebspacesSourceServer(
			node_id, self._get_source_servers()[node_id],
			self._get_migrator_server(), '12.1', self.conn.mn_server
		)

	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 move webspaces mode
			resellers=set(),
			customers_mapping={},
			plans={None: set()}
		)

	def _get_subscription_target_services(self, check_all_subscriptions_exist=True):
		return {
			self.global_context.webspace_name: SubscriptionTargetServices(
				web_ips=Ips(self.global_context.webspace_ipv4, self.global_context.webspace_ipv6),
				mail_ips=Ips(None, None),
				db_servers=Ips(None, None),
				dns_ips=Ips(None, None)
			)
		}