import shutil

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


class SaveConverted(CommonAction):
	def __init__(self, subscription_backup):
		"""Class constructor

		Arguments:
		- subscription_backup - object that can retrieve subscription backup
		  object for each subscription, list of servers with backups
		"""
		self._subscription_backup = subscription_backup

	def get_description(self):
		return "Save converted backup to file"

	def get_failure_message(self, global_context):
		return "Failed to save converted backup to file"

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

	def run(self, global_context):
		server_settings = self._subscription_backup.iter_server_settings(
			global_context
		) 
		for settings in server_settings:
			# overwrite converted backup file with data from converted backup object
			converted_filename = global_context.session_files.get_path_to_converted_plesk_backup(settings.id)
			tmp_filename = "%s.tmp" % (converted_filename)
			backup = global_context.load_converted_plesk_backup(settings)
			with open(tmp_filename, 'wb') as backup_file: 
				backup.save(backup_file) 
			shutil.copy2(tmp_filename, converted_filename) 
