import logging
import shutil

from parallels.common.actions.base.common_action import CommonAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.utils import between_inclusive
from parallels.common.utils.yaml_utils import read_yaml


logger = logging.getLogger(__name__)


class MergeApplications(CommonAction):
	def get_description(self):
		return "Merge information about APS web applications into backup"

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return "Failed to merge information about APS web applications into backup"

	def get_logging_properties(self):
		return LoggingProperties(compound=False)

	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 run(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		for source_id, settings in global_context.conn.get_source_plesks().iteritems():
			source_server = global_context.conn.get_source_node(source_id)
			if source_server.is_windows() and between_inclusive(source_server.plesk_version, (10, 3), (11, 1)):
				applications_str = read_yaml(
					global_context.session_files.get_path_to_applications_filename(source_id)
				)

				backup = global_context.load_raw_plesk_backup(settings)
				backup.replace_applications(applications_str)

				backup_filename = global_context.session_files.get_path_to_raw_plesk_backup(source_id)
				tmp_filename = '%s.tmp' % backup_filename
				with open(tmp_filename, 'wb') as fp:
					backup.save(fp)

				shutil.copy2(tmp_filename, backup_filename)
