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
from parallels.core.utils.common.xml import elem, text_elem

DomainTemplateInfo = namedtuple('DomainTemplateInfo', ('id', 'name'))


class DomainTemplateOperator(object):
    class Get(namedtuple('Get', ('filter', 'dataset'))):
        class FilterAll(object):
            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(object):
            GEN_SETUP = "gen_setup"
            values = [GEN_SETUP]
            
        operator_name = 'exp_plesk_tmpl_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 parse_result_set(elem, cls._parse_data)

        @classmethod
        def _parse_data(cls, elem):
            return DomainTemplateInfo(
                id=int(elem.findtext('id')),
                name=elem.findtext('data/gen_setup/name')
            )

