from collections import namedtuple

from parallels.plesk.utils.xml_rpc.expand.core import parse_result_set
from parallels.core.utils.common import sort_list_by_another, if_not_none
from parallels.core.utils.common.xml import elem, text_elem

PleskClientInfo = namedtuple('PleskClientInfo', ('id', 'gen_info'))
PleskClientGenInfo = namedtuple('PleskClientGenInfo', ('login', 'pname', 'email'))


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

		class FilterByServerId(namedtuple('ServerId', ('server_id'))):
			def inner_xml(self):
				return [text_elem('server_id', self.server_id)]

		class Dataset(object):
			GEN_INFO = 'gen_info'
			LIMITS = 'limits'
			PERMISSIONS = 'permissions'
			PREFERENCES = 'preferences'
			SITEAPP = 'siteapp'
			STAT = 'stat'
			IPPOOL = 'ippool'

			values = [GEN_INFO, LIMITS, PERMISSIONS, PREFERENCES, SITEAPP, STAT, IPPOOL]
			
		operator_name = 'exp_plesk_client'
		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 PleskClientInfo(
				id=int(elem.findtext('id')),
				gen_info=if_not_none(elem.find('data/gen_info'), lambda gen_info_node:
					PleskClientGenInfo(
						login=gen_info_node.findtext('login'),
						pname=gen_info_node.findtext('pname'),
						email=gen_info_node.findtext('email')
					)
				)
			)
