from parallels.plesk.source.plesk import messages
import logging
import shutil

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


logger = logging.getLogger(__name__)


class MergeApplications(CommonAction):
	def get_description(self):
		return messages.ACTION_MERGE_APPLICATIONS_DESCRIPTION

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

	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.core.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_dump(settings)
				backup.replace_applications(applications_str)

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

				shutil.copy2(tmp_filename, backup_filename)
