from parallels.source.custom import messages
import logging

from parallels.core.actions.base.common_action import CommonAction
from parallels.source.custom.backup_creator import BackupCreator

logger = logging.getLogger(__name__)


class CreateFromLight(CommonAction):
	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:rtype: basestring
		"""
		return messages.ACTION_CREATE_FULL_BACKUP_FAILURE

	def get_description(self):
		"""
		:rtype: basestring
		"""
		return messages.ACTION_CREATE_FULL_BACKUP_DESCRIPTION

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:rtype: None
		"""
		backup_creator = BackupCreator()
		conn = global_context.conn
		""":type conn: parallels.source.custom.connections.MigratorConnections"""
		with global_context.migrator_server.runner() as local_runner:
			for light_backup_config in conn.iter_source_light_backup_configs():
				dump_filename = global_context.session_files.get_path_to_full_backup_created_from_light(
					light_backup_config.source_id
				)
				if (
					local_runner.file_exists(dump_filename) and
					not global_context.options.reload_source_data
				):
					logger.info(u"Using the existing dump '{dump_filename}' for '{source_id}'".format(
						dump_filename=dump_filename, source_id=light_backup_config.source_id
					))
				else:
					logger.info("Create full backup for '%s'", light_backup_config.source_id)

					backup_creator.write_full_backup(
						light_backup_config, dump_filename,
						database_servers=list(global_context.conn.iter_database_servers())
					)
