import logging

from parallels.common.migrator import SubscriptionTargetServices
from parallels.plesks_migrator.migrator import Migrator as PleskMigrator
from parallels.shm_move_webspaces.connections import PPAMoveWebspacesWebSnSourceConnections
from parallels.shm_move_webspaces.importer import PPAMoveWebspacesImporter
from parallels.shm_move_webspaces.source_server import PPAMoveWebspacesSourceServer
from parallels.shm_move_webspaces.workflow import PPAMoveWebspacesWorkflow
from parallels.shm_move_webspaces.global_context import PPAMoveWebspacesGlobalMigrationContext
from parallels.common.migration_list import MigrationListData, SubscriptionMappingInfo, SubscriptionIPMapping
from parallels.plesk_api.operator.subscription import Ips
from parallels.target_panel_plesk.converter.converter import PleskConverter
from parallels.target_panel_ppa_web_sn.panel import PPAMoveWebspacesTargetPanel
from parallels.utils 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)
			)
		}