import logging
import posixpath

import parallels
from parallels.core.utils.common import cached
from parallels.core.utils import plesk_utils
from parallels.core.plesk_backup.data_model import DatabaseServer
from parallels.source.legacy.migrator import PmmUnixMigrator
from parallels.source.ppcpl.connections import PPCPLMigratorConnections
from parallels.source.ppcpl import settings
from parallels.source.ppcpl.pmm_agent import PPCPLPmmMigrationAgent
from parallels.source.ppcpl.workflow import FromPPCPLWorkflow
from parallels.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.config, self._get_target_panel())

	def _create_workflow(self):
		return FromPPCPLWorkflow()

	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.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,
		)
