from parallels.core import messages
import logging
from parallels.core.utils.common_constants import ADMIN_ID

from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.migration_list.utils import get_migration_list_file_location

logger = logging.getLogger(__name__)


class GenerateMigrationList(CommonAction):
	def get_description(self):
		return messages.ACTION_GENERATE_MIGRATION_LIST

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		return messages.FAILED_GENERATE_MIGRATION_LIST_FILE

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		subscription_names = []
		reseller_logins = []

		for _, source_backup in global_context.migrator.iter_shallow_dumps():
			subscription_names += [s.name for s in source_backup.iter_all_subscriptions()]
			reseller_logins += [
				r.login
				for _, _, r in source_backup.iter_all_subscriptions_with_owner_and_reseller()
				if r is not None
			]

		logger.info(messages.CHECKING_IF_WEBSPACES_EXIST_IN_TARGET)
		target_webspaces = global_context.import_api.list_webspaces_brief(subscription_names)
		logger.info(messages.BROWSING_SERVICE_TEMPLATES_WHICH_COULD_USED)
		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(ADMIN_ID)
			]
		}
		target_addon_service_templates = {
			None: [
				st.name
				for st in global_context.import_api.get_addon_service_template_list(ADMIN_ID)
			]
		}
		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,
			include_source_plans=global_context.target_panel_obj.use_source_plans()
		)
		logger.info(messages.MIGRATION_LIST_FILE_TEMPLATE_IS_SAVED, migration_list_file)
