import logging
import posixpath

import parallels
from parallels.utils import cached
from parallels.common.utils import plesk_utils
from parallels.common.plesk_backup.data_model import DatabaseServer
from parallels.pmm_unix_migrator.migrator import PmmUnixMigrator
from parallels.ppcpl_migrator.connections import PPCPLMigratorConnections
from parallels.ppcpl_migrator import settings
from parallels.ppcpl_migrator.pmm_agent import PPCPLPmmMigrationAgent
from parallels.ppcpl_migrator.workflow import FromPPCPLWorkflow
from parallels.ppcpl_migrator.global_context import PPCPLGlobalMigrationContext


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

	def __init__(self, config):
		super(Migrator, self).__init__(config, settings)
		self.global_context.pmm_agent = self._get_pmm_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_pmm_agent(self):
		migrator_pmm_dir = posixpath.join(
			plesk_utils.get_migrator_root_path(parallels.ppcpl_migrator),
			'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.pmm_agent.get_mysql_admin_password(),
			dbtype='mysql',
			is_default=True,
		)
