from parallels.common import messages
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 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.common.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_path_to_converted_plesk_backup(backup_id)
			tmp_filename = "%s.tmp" % converted_filename
			backup = global_context.load_converted_plesk_backup(backup_id)
			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()
