from parallels.core import messages
import shutil

from parallels.core.actions.base.common_action import CommonAction
from parallels.core.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 messages.ACTION_SAVE_CONVERTED_BACKUPS

	def get_failure_message(self, global_context):
		return messages.FAILED_SAVE_CONVERTED_BACKUP_FILE

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

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		backup_ids = self._subscription_backup.get_backup_ids(global_context)
		for backup_id in backup_ids:
			# overwrite converted backup file with data from converted backup object
			converted_filename = global_context.session_files.get_converted_dump_filename(backup_id)
			tmp_filename = "%s.tmp" % converted_filename
			backup = global_context.load_converted_dump(backup_id)
			with open(tmp_filename, 'wb') as backup_file: 
				backup.save(
					backup_file,
					'zip' if global_context.conn.target.is_windows else 'tar'
				)
			shutil.copy2(tmp_filename, converted_filename) 
			backup.close()
