from parallels.core.utils.plesk_utils import IPAddressInfo
from parallels.shm_web_sn.source.shm_web_sn import messages
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_cli_runner import PleskCLIRunnerCLI
from parallels.plesk.import_api.model import WebspaceStatus, PleskWebspaceInfo, PleskSubscriptionInfo

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.core.global_context.GlobalMigrationContext
		"""
		raw_target_subscriptions = []
		webspaces = []
		domain_names = []

		plesk_cli_runner = PleskCLIRunnerCLI(global_context.conn.target.plesk_server)

		# Check webspace existence. Expect 0 exit code if webspace exists, 2 - object not found
		# Currently subscription CLI has an error and returns 1 for OBJECT_NOT_EXISTS error
		# Check exit code for non zero value until the issue will be fixed
		exit_code, stdout, stderr = plesk_cli_runner.run_unchecked('subscription', ['-i', global_context.webspace_name])

		if exit_code == 0:
			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
		)
		global_context.target_existing_objects = model
		target_filename = global_context.session_files.get_path_to_existing_objects_model()
		write_yaml(target_filename, model)
		return model
