import logging

from parallels.core.actions.base.common_action import CommonAction
from parallels.core.existing_objects_model import ExistingObjectsModel
from parallels.core.utils.yaml_utils import write_yaml
from parallels.core.utils.plesk_utils import IPAddressInfo
from parallels.plesk.import_api.model import WebspaceStatus, PleskWebspaceInfo, PleskSubscriptionInfo

from parallels.shcm_web_sn.source.shcm_web_sn import messages

logger = logging.getLogger(__name__)


class FetchTargetAction(CommonAction):
	def get_description(self):
		return messages.FETCH_DATA_FROM_TARGET_PPA_WEB_SN

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		return messages.FAILED_TO_FETCH_DATA_FROM_TARGET_PPA_WEB_SN

	def run(self, global_context):
		"""
		:type global_context: parallels.shcm_web_sn.source.shcm_web_sn.global_context.SHCMMoveWebspacesGlobalMigrationContext
		"""
		raw_target_subscriptions = []
		webspaces = []
		domain_names = []

		# Report webspace as already existing to prevent migrator from creating it itself before pmmcli
		webspace = PleskWebspaceInfo(
			webspace_id=0,  # Not an actual value, as it used for sorting only
			name=global_context.webspace_name,
			subscription_id=0,
			owner_id=0,
			status=WebspaceStatus.ACTIVE,
			htype=None,
		)
		webspaces.append(webspace)

		subscription = PleskSubscriptionInfo(
			subscription_id=0,
			owner_id=0,
			st_id=0,
			name=global_context.webspace_name,
			is_active=True,
		)
		raw_target_subscriptions.append(subscription)

		domain_names.append(global_context.webspace_name)

		ip_addresses = []
		if global_context.webspace_ipv4:
			ip_addresses.append(IPAddressInfo(global_context.webspace_ipv4_type, global_context.webspace_ipv4, None))

		if global_context.webspace_ipv6:
			ip_addresses.append(IPAddressInfo(global_context.webspace_ipv6_type, global_context.webspace_ipv6, None))

		model = ExistingObjectsModel(
			resellers={},
			customers={},
			service_templates=[],
			addon_service_templates=[],
			raw_target_subscriptions=raw_target_subscriptions,
			webspaces=webspaces,
			auxiliary_user_roles=[],
			auxiliary_users=[],
			plesk_subscriptions=domain_names,
			plesk_sites={},
			plesk_site_aliases={},
			plesk_subdomains={},
			ip_addresses=ip_addresses
		)

		target_filename = global_context.session_files.get_path_to_existing_objects_model()
		write_yaml(target_filename, model)

		global_context.target_existing_objects = model

		return model
