from parallels.pvps import messages
import logging

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

logger = logging.getLogger(__name__)


class CreatePleskSubscription(SubscriptionAction):
	def get_description(self):
		return messages.CREATE_PLESK_SUBSCRIPTION

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

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

	def run(self, global_context, subscription):
		"""
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		if check_if_subscription_exists(subscription.panel_target_server.plesk_api(), subscription.name):
			logger.debug(messages.SUBSCRIPTION_ALREADY_EXISTS, 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.core.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
