from parallels.core import messages
from collections import namedtuple
import logging

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

logger = logging.getLogger(__name__)


class ImportClients(CommonAction):
	def get_description(self):
		return messages.CREATE_CLIENTS_IN_TARGET_PANEL

	def get_failure_message(self, global_context):
		return (
			messages.FAILED_CREATE_CLIENTS_TARGET_PANEL_MIGRATION)

	def run(self, global_context):
		"""
		:type global_context: parallels.core.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.core.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,
			messages.FAILED_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(messages.CREATE_CLIENT_S_OWNED_BY_ADMINISTRATOR, client.login)
					else:
						logger.info(messages.CREATE_CLIENT_S_OWNED_BY_RESELLER, client.login, reseller_login)
					client_id, warnings = global_context.import_api.create_customer(reseller_id, client)
					for warning in warnings:
						global_context.safe.fail_client(
							reseller_login, client.login, warning,
							is_critical=False,
							severity=Problem.WARNING
						)

					target_client = CreatedClient(id=client_id)
					global_context.target_existing_objects.customers[client.login] = target_client
					client.target_client = target_client
			else:
				logger.debug(messages.CLIENT_LOGIN_S_ALREADY_EXISTS_SKIP, client.login)

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