import sys
import logging
from parallels.common.utils import migrator_utils

logger = logging.getLogger(__name__)

def print_hosting_report(
	report, check_type, checks_map, checks_order, successful_message,
	save_report_function=None
):
	"""Print report and summary of hosting checks

	Print report and summary of hosting checks with logging module, put some info
	into files

	Arguments:
	- report - hosting report, instance of checking.Report
	- check_type - what we check: service or subscription
	- checks_map - map for checks name
	- checks_order - list of checks in order
	- save_report_function - function which accepts contents of a report 
	  (as a string) and returns filename it saved the report to
	"""
	def subscriptions_count(report, check_type):
		count = 0
		for child_id, child in report.children.iteritems():
			if child_id[0] == check_type:
				count += 1
			count += subscriptions_count(child, check_type)
		return count

	def check_counts(report, check_type):
		total = 0
		failed = 0
		warnings = 0

		for child_id, child in report.children.iteritems():
			(
				children_total, 
				children_warnings, 
				children_failed
			) = check_counts(child, check_type)
			total += children_total
			warnings += children_warnings
			failed += children_failed
			if child_id[0] == check_type:
				total += 1
				if child.has_errors():
					failed += 1
				if child.has_warnings():
					warnings += 1
		return (total, warnings, failed)

	def failed_subscriptions_count(report, check_type):
		count = 0
		for child_id, child in report.children.iteritems():
			if child_id[0] == check_type \
				and child.has_errors():
					count +=1
			count += failed_subscriptions_count(child, check_type)
		return count

	subscriptions_count = subscriptions_count(report, check_type)
	failed_subscriptions_count = failed_subscriptions_count(report, check_type)

	report_string = migrator_utils.format_report(
		report, show_no_issue_branches=True
	)
	logger.info("\n" + report_string)
	if save_report_function is not None:
		report_filename = save_report_function(report_string)
		logger.info(
			"The report was saved into the file %s",
			report_filename
		)

	logger.info(u"******************** Summary ********************")

	stats = list()
	for check_name in checks_order:
		total, warnings, failed = check_counts(report, checks_map[check_name])
		if total != 0:
			stats.append((
				check_name, 
				total, 
				total - failed - warnings, 
				warnings, 
				failed
			))

	if len(stats) > 0:
		logger.info(
			u"Operation finished successfully for %s out of %s %s",
			subscriptions_count - failed_subscriptions_count,
			subscriptions_count,
			'subscriptions' if check_type == 'Subscription' else 'services'
		)

		def print_stats_line(name, total, success, warnings, failed):
			logger.info(u"%-20s %-5s %-10s %-8s %-6s" % (
				name, total, success, warnings, failed
			))

		print_stats_line(
			u"Checked objects", u"Total", u"Successful", "Warnings", u"Failed"
		)
		for name, total, success, warnings, failed in stats:
			print_stats_line(name, total, success, warnings, failed)

		if report.has_issues():
			sys.exit(1)
		else:
			logger.info(successful_message)
	else:
		logger.info("No objects were checked")

def print_backup_hosting_report(report, save_report_function=None):
	checks_map = {
		'Apache web sites': 'Apache web site',
		'IIS web sites': 'IIS web site',
		'DNS zones': 'DNS zone',
		'Mail domains': 'Mail domain',
		'FTP service': 'FTP service',
		'SSH service': 'SSH service',
		'RDP service': 'RDP service',
		'Database service': 'Database service',
	}
	checks_order = [ 
		'Apache web sites', 'IIS web sites', 'DNS zones', 
		'Mail domains', 'FTP service', 'SSH service', 'RDP service',
		'Database service' 
	]

	print_hosting_report(
		report,
		'Subscription',
		checks_map,
		checks_order,
		u"All transferred domains are working correctly.",
		save_report_function
	)

def print_service_hosting_report(report, save_report_function=None):
	checks_map = {
		'Service': 'Service',
	}
	checks_order = ['Service']

	print_hosting_report(
		report,
		'Service',
		checks_map,
		checks_order,
		u"All services are working correctly.",
		save_report_function
	)
