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

PleskDomainInfo = namedtuple('PleskDomainInfo', ('id', 'name', 'client_id', 'server_id', 'tmpl_id'))

class PleskDomainOperator:
	class Get(namedtuple('Get', ('filter', 'dataset'))):
		class FilterAll:
			def inner_xml(self): return [elem('all')]
		class FilterByServerId(namedtuple('ServerId', ('server_id'))):
			def inner_xml(self):
				return [text_elem('server_id', self.server_id)]

		class Dataset:
			values = []
			
		operator_name = 'exp_plesk_domain'
		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 PleskDomainInfo(
				id=int(elem.findtext('id')),
				name=elem.findtext('name'),
				client_id=int(elem.findtext('client_id')),
				server_id=int(elem.findtext('server_id')),
				tmpl_id=if_not_none(elem.findtext('tmpl_id'), int)
			)

