import logging
from parallels.common.actions.base.common_action import CommonAction
from parallels.common.existing_objects_model import ExistingObjectsModel
from parallels.common.utils.yaml_utils import write_yaml
from parallels.common.utils.plesk_cli_runner import PleskCLIRunnerCLI
from parallels.target_panel_plesk.import_api.model import WebspaceStatus, PleskWebspaceInfo, PleskSubscriptionInfo

logger = logging.getLogger(__name__)


class FetchTargetAction(CommonAction):
	def get_description(self):
		return u'Fetch data from target PPA Web SN'

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return u'Failed to fetch data from target PPA Web SN'

	def run(self, global_context):
		"""
		:type global_context: parallels.common.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
