import logging
import os

import parallels.plesks_migrator
from parallels.utils import between_inclusive
from parallels.common.actions.base.common_action import CommonAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.common.utils import migrator_utils
from parallels.common.utils.yaml_utils import write_yaml


logger = logging.getLogger(__name__)


class FetchApplicationsAction(CommonAction):
	def get_description(self):
		return "Fetch information about APS web applications"

	def get_failure_message(self, global_context):
		return "Failed to fetch information about APS web applications"

	def get_logging_properties(self):
		return LoggingProperties(compound=False)

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed, migration tool won't run the next operations.

		:rtype: bool
		"""
		return False

	def run(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		for source_id in global_context.conn.get_source_plesks():
			logger.debug(u"Fetch information about web applications installed on '%s'", source_id)

			source_server = global_context.conn.get_source_node(source_id)
			with source_server.runner() as runner_source:

				use_external_applications_file = ( 
					source_server.is_windows()
					and 
					between_inclusive(
						source_server.plesk_version,
						(10, 3), (11, 1)
					)
				)

				if not use_external_applications_file:
					continue

				applications_filename = global_context.session_files.get_path_to_applications_filename(source_id)
				
				if not global_context.options.reload_source_data and os.path.exists(applications_filename):
					continue

				script_name = "WindowsApsBackup.php"
				remote_script_path = source_server.get_session_file_path(script_name)
				runner_source.upload_file(
					migrator_utils.get_package_extras_file_path(
						parallels.plesks_migrator, script_name
					), 
					remote_script_path
				)
				applications = runner_source.sh(
					ur'cmd.exe /C "{plesk_dir}\admin\bin\php.exe -dauto_prepend_file="" -d display_errors="On" {windows_aps_backup}"',
					dict(plesk_dir=source_server.plesk_dir, windows_aps_backup=remote_script_path)
				)

				write_yaml(applications_filename, applications)
