from collections import namedtuple

from parallels.common.migration_list import MigrationList, BaseMigrationListLineHandler


BillingMigrationListData = namedtuple('BillingMigrationListData', (
	# dict with keys - subscription names, values - PPAB plan ID to import subscription to
	# we match PPAB plans by ID because there could be 2 plans with the same name, but different ID
	'billing_plan_ids',
))

class HSphereMigrationList(MigrationList):
	allowed_labels = ['plan', 'customer', 'reseller', 'billing plan id']

	@classmethod
	def read_billing_info(cls, fileobj):
		class Handler(BaseMigrationListLineHandler):
			def __init__(self, allowed_labels):
				super(Handler, self).__init__(allowed_labels)
				self.billing_plan_id = None
				self.data = BillingMigrationListData(billing_plan_ids={})

			def handle_label(self, label, value, line_number):
				if label == 'billing plan id':
					self.billing_plan_id = value
					return True
				else:
					return super(Handler, self).handle_label(label, value, line_number)

			def handle_subscription(self, subscription, line_number):
				if self.billing_plan_id is not None:
					self.data.billing_plan_ids[subscription] = self.billing_plan_id

		handler = Handler(cls.allowed_labels)
		cls._read(fileobj, handler)
		return (handler.data, handler.errors)

