import logging

from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.utils.plesk_api_utils import check_if_subscription_exists
from parallels.common.utils.plesk_cli_runner import PleskCLIRunnerCLI
from parallels.target_panel_plesk.import_api.import_api_base import PleskBaseImportAPI
from parallels.utils import generate_random_password

logger = logging.getLogger(__name__)


class CreatePleskSubscription(SubscriptionAction):
	def get_description(self):
		return "Create Plesk subscription in target panel"

	def get_failure_message(self, global_context, subscription):
		"""
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return (
			"Failed to create Plesk subscription '%s' in target panel"
		) % (subscription.name,)

	def filter_subscription(self, global_context, subscription):
		"""
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return True

	def run(self, global_context, subscription):
		"""
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		if check_if_subscription_exists(subscription.panel_target_server.plesk_api(), subscription.name):
			logger.debug(u"Subscription '%s' already exists in the target panel", subscription.name)
			return

		plesk_cli_runner = PleskCLIRunnerCLI(subscription.panel_target_server)
		utility_name = 'subscription'
		command_arguments = self._create_subscription_command_args(subscription)
		plesk_cli_runner.run(utility_name, command_arguments)

	def _create_subscription_command_args(self, subscription):
		"""
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		if subscription.model.sysuser_login is not None:
			sysuser_login = subscription.model.sysuser_login
		else:
			sysuser_login = PleskBaseImportAPI.generate_random_login()

		command_arguments = [
			'--create',
			subscription.name,
			'-hosting', 'true',
			'-hst_type', 'phys',
			'-login', sysuser_login,
			'-passwd', generate_random_password(),
			'-ip', subscription.panel_target_server.ip(),
			'-do-not-apply-skeleton',
			'-notify', 'false'
		]
		return command_arguments
