from collections import namedtuple

from .. import core
from parallels.utils import sort_list_by_another, if_not_none
from parallels.utils.xml import elem, text_elem

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

class PleskClientOperator:
	class Get(namedtuple('Get', ('filter', 'dataset'))):
		class FilterAll:
			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:
			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 [core.Result.parse(r, cls._parse_data) for r in elem.findall('result')]
		
		@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')
					)
				)
			)

