from collections import namedtuple

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

PlanInfo = namedtuple('PlanInfo', ('plan_id', 'name', 'owner_id'))

ServicePlanLimits = namedtuple('ServicePlanLimits', (
	'overuse', 
	'limits' # list of ServicePlanLimit
))
ServicePlanLimit = namedtuple('ServicePlanLimit', ('name', 'value',))
ServicePlanPermission = namedtuple('ServicePlanPermission', ('name', 'value',))

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

	class Get(core.operation_with_filter('Get', ('owner_id', 'owner_all',))):
		operator_name = 'service-plan'
		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),
				elem('owner-all') if self.owner_all else None
			)

		@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'))
			name = elem.findtext('name')
			owner_id = if_not_none(elem.findtext('owner-id'), int)
			return PlanInfo(plan_id=plan_id, name=name, owner_id=owner_id)

	class Add(core.operation('Add', ('name', 'owner_login', 'limits', 'permissions'))):
		operator_name = 'service-plan'
		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.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'))
		
