from parallels.plesk.source.plesk import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.hosting_settings.import_backups import ImportedBackups
from parallels.core.utils.restore_hosting_utils import get_restore_hosting_utils


class RestoreApplications(SubscriptionAction):
	def get_description(self):
		return messages.ACTION_RESTORE_APS_APPLICATIONS

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.ACTION_RESTORE_APS_APPLICATIONS_FAILURE % subscription.name

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed for a subscription, migration tool
		won't run the next operations for the subscription.

		:rtype: bool
		"""
		return False

	def filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return subscription.converted_dump.has_aps

	def run(self, global_context, subscription):
		"""Restore APS applications after copy web content so all configs updated according to new configuration.

		For example, if database server's IP has been changed, wp-config.php file of Wordpress APS application should 
		be updated accordingly. We should do this after copy-content step, otherwise configuration
		files are overwritten by copy-content step.

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		imported_backup = ImportedBackups.get_instance().get_by_backup(subscription.converted_server_dump)
		subscription_backup_xml = imported_backup.get_domain_xml_path(subscription.name)
		additional_env_vars = global_context.target_panel_obj.get_restore_hosting_additional_env_vars(
			global_context, subscription
		)
		restore_hosting_utils = get_restore_hosting_utils(subscription.panel_target_server)
		restore_hosting_utils.restore_hosting_settings(
			subscription.name, subscription_backup_xml, global_context.safe,
			settings_description=messages.APS_APPLICATIONS_HOSTING_DESCRIPTION,
			restore_siteapps_only=True,
			additional_env_vars=additional_env_vars
		)
