import shutil

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


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):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		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,
					'zip' if (
						global_context.conn.target.is_windows
						and
						global_context.target_panel == TargetPanels.PPA_WEB_SN
					) else 'tar'
				)
			shutil.copy2(tmp_filename, converted_filename) 
			backup.close()
