from parallels.core import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties \
	import LoggingProperties
from parallels.core.utils.common import group_by_id


class FixWindowsPHP53ISAPI(SubscriptionBackupAction):
	"""PHP 5.3 and ISAPI combination is not supported on Windows. Remove it from backup.

	Old Plesk versions allowed to set this invalid combination of options. Actually it worked
	just as PHP 5.3 + FastCGI. But in source database we get such combination, and during restoration we get
	"Wrong value of php_handler_type, it can take only CGI application, FastCGI application, ISAPI extension"
	message for such combination. To avoid this warning and explicitly set the actual value from source,
	we change PHP 5.3 + ISAPI to PHP 5.3 + FastCGI.

	Do that silently not to overload customer with useless notices.
	"""
	def get_description(self):
		return messages.SWITCH_PHP_ISAPI_PHP_FASTCGI_FOR

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.FAILED_SWITCH_PHP_ISAPI_PHP_FASTCGI % subscription.name

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed for a subscription, migration tool
		won't run the next operations for the subscription.

		:rtype: bool
		"""
		return False

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

	def _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		for domain in subscription.converted_dump.iter_domains():
			if domain.scripting is None:
				continue

			options_by_name = group_by_id(domain.scripting.options, lambda o: o.name)
			php_version_option = options_by_name.get('php_version')
			php_handler_type = options_by_name.get('php_handler_type')

			if php_version_option is None or php_handler_type is None:
				continue

			if php_version_option.value == '5.3' and php_handler_type.value == 'isapi':
				php_handler_type.value = 'fastcgi'
