from collections import namedtuple

from .. import core
from parallels.utils.xml import text_elem, elem, seq

AddonPlanInfo = namedtuple('AddonPlanInfo', ('plan_id', 'guid', 'name'))

ServicePlanAddonLimit = namedtuple('ServicePlanAddonLimit', ('name', 'value',))
ServicePlanAddonPermission = namedtuple('ServicePlanAddonPermission', ('name', 'value',))

class ServicePlanAddonOperator:
	FilterAll = core.FilterAll
	FilterById = core.declare_filter('FilterById', 'id')
	FilterByGuid = core.declare_filter('FilterByGuid', 'guid')

	class Get(core.operation_with_filter('Get', ('owner_id',))):
		operator_name = 'service-plan-addon'
		operation_name = 'get'
		min_api_version = '1.6.3.0'
		max_api_version = '1.6.5.0'

		def data_xml(self):
			return seq(
				text_elem('owner-id', self.owner_id),
			)

		@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):
			plan_id = int(elem.findtext('id'))
			guid = elem.findtext('guid')
			name = elem.findtext('name')
			return AddonPlanInfo(plan_id=plan_id, guid=guid, name=name)

	class Add(core.operation('Add', ('name', 'owner_login', 'limits', 'permissions'))):
		operator_name = 'service-plan-addon'
		operation_name = 'add'
		min_api_version = '1.6.3.0'
		max_api_version = None

		def inner_xml(self):
			return seq(
				text_elem('name', self.name),
				text_elem('owner-login', self.owner_login),
				elem('limits', [
					elem('limit', [text_elem('name', limit.name), text_elem('value', limit.value)])
					for limit in self.limits
				]),
				elem('permissions', [
					elem('permission', [text_elem('name', permission.name), text_elem('value', permission.value)])
					for permission in self.permissions
				]),
			)

		@classmethod
		def parse(cls, elem):
			return core.Result.parse(elem.find('result'))
		
