from collections import namedtuple
import logging

from parallels.common.actions.base.common_action import CommonAction
from parallels.utils import if_not_none
from parallels.common.utils.common_constants import ADMIN_ID

logger = logging.getLogger(__name__)


class ImportClients(CommonAction):
	def get_description(self):
		return "Create clients in target panel"

	def get_failure_message(self, global_context):
		return (
			"Failed to create clients on target panel, "
			"migration can not proceed to the next steps"
		)

	def run(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""

		model = global_context.target_model

		for client in model.clients.itervalues():
			self._create_client(global_context, client, None)

		for reseller in model.resellers.itervalues():
			for client in reseller.clients:
				self._create_client(global_context, client, reseller)

	@staticmethod
	def _create_client(global_context, client, reseller):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""

		reseller_login = if_not_none(reseller, lambda r: r.login)
		if reseller is None:
			reseller_id = ADMIN_ID
		else:
			reseller_id = global_context.target_existing_objects.resellers[reseller.login].id

		with global_context.safe.try_client(
			reseller_login,
			client.login,
			u"Failed to create client in target panel"
		):
			if client.login not in global_context.target_existing_objects.customers:
				if client.login != reseller_login:
					if reseller_login is None:
						logger.info(u"Create client '%s' owned by administrator", client.login)
					else:
						logger.info(u"Create client '%s' owned by reseller '%s'", client.login, reseller_login)
					client_id = global_context.import_api.create_customer(reseller_id, client)

					target_client = CreatedClient(id=client_id)
					global_context.target_existing_objects.customers[client.login] = target_client
					client.target_client = target_client
			else:
				logger.debug("Client with login '%s' already exists, skip creating", client.login)

CreatedClient = namedtuple('CreatedClient', ('id',))
