from contextlib import closing

from parallels.ppa.actions.hosting_settings.convert.dns \
	import DNS as ActionHostingSettingsConvertPPADNS
from parallels.plesk.utils.xml_rpc.plesk.operator.dns import DnsRecord


class DNS(ActionHostingSettingsConvertPPADNS):
	def _get_source_dns_template(self, global_context, subscription):
		"""Make server dns template like dns server template in Plesk.

		Backup argument is not used for hsphere migrator. it's used in Plesks migrators.

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		server_dns_template = [
			DnsRecord(id=None, rec_type='A', src='<domain>', dst='<ip>', opt=''),
			DnsRecord(id=None, rec_type='A', src='*.<domain>', dst='<ip>', opt=''),
			DnsRecord(id=None, rec_type='TXT', src='<domain>', dst='v=spf1 a mx -all', opt='')
		]

		with closing(global_context.conn.hsphere.db()) as cursor:
			cursor.execute(u"SELECT name FROM l_server WHERE group_id = 3")  # 3 - mail servers
			for mail_server_name in cursor.fetchall():
				server_dns_template.append(DnsRecord(
					id=None, rec_type='MX', src='<domain>', dst=mail_server_name[0], opt='10'
				))
				server_dns_template.append(DnsRecord(
					id=None, rec_type='CNAME', src='mail.<domain>', dst=mail_server_name[0], opt=''
				))

		return server_dns_template 
