from parallels.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.target.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_ppa_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_ppa_subscriptions.append(subscription)

			domain_names.append(global_context.webspace_name)

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

		target_filename = global_context.migrator._get_session_file_path('ppa_existing_objects.yaml')
		write_yaml(target_filename, model)
		return model
