import logging
import posixpath

import parallels
from parallels.core.utils.common import cached
from parallels.core.utils import plesk_utils
from parallels.core.dump.data_model import DatabaseServer
from parallels.plesk.source.legacy.migrator import PmmUnixMigrator
from parallels.plesk.source.ppcpl.connections import PPCPLMigratorConnections
from parallels.plesk.source.ppcpl import settings
from parallels.plesk.source.ppcpl.pmm_agent import PPCPLPmmMigrationAgent
from parallels.plesk.source.ppcpl.global_context import PPCPLGlobalMigrationContext


class Migrator(PmmUnixMigrator):
	logger = logging.getLogger(__name__)

	def __init__(self, config):
		super(Migrator, self).__init__(config, settings)
		self.global_context.dump_agent = self._get_dump_agent()

	def _load_connections_configuration(self):
		return PPCPLMigratorConnections(self.global_context, self._get_target_panel())

	def _create_global_context(self):
		context = PPCPLGlobalMigrationContext()
		context.source_has_dns_forwarding = False
		return context

	@cached  # to avoid re-deploying, have a single PMM agent object
	def _get_dump_agent(self):
		migrator_pmm_dir = posixpath.join(
			plesk_utils.get_migrator_root_path(parallels.plesk.source.ppcpl),
			'extras',
			'pmm'
		)
		return PPCPLPmmMigrationAgent(
			self.global_context,
			self.conn.ppcpl,
			migrator_pmm_dir,
			self._get_settings(),
		)

	# ======================== databases =====================================

	def _get_src_db_server(self, db, backup):
		return DatabaseServer(
			None,
			host='localhost',
			port='3306',
			login='root',
			password=self.global_context.dump_agent.get_mysql_admin_password(),
			dbtype='mysql',
			is_default=True,
		)
