import logging
from collections import defaultdict

from parallels.common import restore_hosting
from parallels.common.actions.base.common_action import CommonAction

logger = logging.getLogger(__name__)

class RestoreApplications(CommonAction):
	def get_description(self):
		return "Restore APS applications"

	def run(self, global_context):
		"""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 acordingly. We should do this after copy-content step, otherwise configuration files are overwritten by copy-content step.
		"""
		logger.info(u"Restore APS applications configuration")

		subscriptions_by_source = defaultdict(list)
		for subscription in global_context.iter_all_subscriptions():
			subscriptions_by_source[subscription.model.source].append(subscription)

		with global_context.conn.target.main_node_runner() as runner:
			for source_id, subscriptions in subscriptions_by_source.iteritems():
				path = global_context.session_files.get_path_to_converted_plesk_backup(source_id)
				backup = subscriptions[0].full_converted_backup

				subscriptions_to_fix_perms = [
					subscription.name
					for subscription in subscriptions
					if subscription.converted_backup.has_aps
				]

				restore_hosting.call_plesk_restore_aps(
					global_context.conn.target, backup, path, runner,
					subscriptions_to_fix_perms, safe=global_context.safe, 
					target_backup_path=global_context.conn.target.main_node_session_file_path('plesk.backup')
				)
