from collections import namedtuple

from parallels.expand_api.core import parse_result_set
from parallels.utils import sort_list_by_another
from parallels.utils.xml import elem

PleskServerData = namedtuple('ServerData', ('id', 'ips'))
IpInfo = namedtuple('IpInfo', ('ip_address'))


class PleskServerOperator(object):
	class Get(namedtuple('Get', ('filter', 'dataset'))):
		class FilterAll(object):
			def inner_xml(self): return []

		class Dataset(object):
			IPPOOL = 'ippool'

			values = [IPPOOL]

		operator_name = 'exp_plesk_server'
		operation_name = 'get'

		def inner_xml(self):
			return [
				elem('filter', self.filter.inner_xml()),
				elem('dataset', [elem(i) for i in sort_list_by_another(self.dataset, self.Dataset.values)])
			]
			
		@classmethod
		def parse(cls, elem):
			return parse_result_set(elem, cls._parse_data)

		@classmethod
		def _parse_data(cls, elem):
			return PleskServerData(
				id=int(elem.findtext('id')),
				ips=[
					IpInfo(ip_address=ip_node.findtext('ip_address'))
					for ip_node in elem.findall('ippool/ip_info')
				]
			)