import logging

from parallels import poa_api
from parallels.common.actions.base.common_action import CommonAction
from parallels.common.actions.migration_list.utils import get_migration_list_file_location

logger = logging.getLogger(__name__)


class GenerateMigrationList(CommonAction):
	def get_description(self):
		return "Generate migration list file"

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return "Failed to generate migration list file"

	def run(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		subscription_names = []
		reseller_logins = []
		for _, plesk_settings in global_context.source_plesks.iteritems():
			backup = global_context.load_shallow_plesk_backup(plesk_settings)
			subscription_names += [s.name for s in backup.iter_all_subscriptions()]
			reseller_logins += [
				r.login
				for _, _, r in backup.iter_all_subscriptions_with_owner_and_reseller()
				if r is not None
			]

		logger.info(u"Checking, if webspaces exist in the target panel")
		target_webspaces = global_context.import_api.list_webspaces_brief(subscription_names)
		logger.info(u"Browsing service templates which could be used for migration")
		target_resellers = global_context.import_api.list_resellers(reseller_logins)
		target_service_templates = {
			None: [
				st.name for st in global_context.import_api.get_service_template_list(poa_api.Identifiers.OID_ADMIN)
			]
		}
		target_addon_service_templates = {
			None: [
				st.name
				for st in global_context.import_api.get_addon_service_template_list(poa_api.Identifiers.OID_ADMIN)
			]
		}
		for r in target_resellers:
			target_service_templates[r.contact.username] = [
				st.name for st in global_context.import_api.get_service_template_list(r.id)
			]
			target_addon_service_templates[r.contact.username] = [
				st.name for st in global_context.import_api.get_addon_service_template_list(r.id)
			]

		migration_list_file = get_migration_list_file_location(global_context)
		global_context.migrator._get_migration_list_class().write_initial(
			migration_list_file,
			global_context.migrator._get_migration_list_source_data(),
			[webspace.name for webspace in target_webspaces],
			target_service_templates,
			include_addon_plans=global_context.import_api.has_addon_service_templates(),
			target_addon_plans=target_addon_service_templates,
			target_panel=global_context.target_panel,
			include_source_plans=global_context.target_panel_obj.use_source_plans()
		)
		logger.info(u"Migration list file template is saved to '%s'", migration_list_file)