import json

EXCLUDE_SELECT_OPTIONS = [
	"naming_series",
	"number_format",
	"float_precision",
	"currency_precision",
	"minimum_password_score",
]


def extract(fileobj, *args, **kwargs):
	"""
	Extract messages from PageType JSON files. To be used to babel extractor
	:param fileobj: the file-like object the messages should be extracted from
	:rtype: `iterator`
	"""
	data = json.load(fileobj)

	if isinstance(data, list):
		return

	pagetype = data.get("name")

	yield None, "_", pagetype, ["Name of a PageType"]

	pagetype_description = data.get("description")
	if pagetype_description:
		yield None, "_", pagetype_description, ["Description of a PageType"]

	messages = []
	fields = data.get("fields", [])
	links = data.get("links", [])

	for field in fields:
		fieldtype = field.get("fieldtype")
		fieldname = field.get("fieldname")
		label = field.get("label")

		if label:
			messages.append((label, f"Label of a {fieldtype} field in PageType '{pagetype}'"))
			_label = label
		else:
			_label = fieldname

		if description := field.get("description"):
			messages.append(
				(description, f"Description of the '{_label}' ({fieldtype}) field in PageType '{pagetype}'")
			)

		if message := field.get("options"):
			if fieldtype == "Select":
				if fieldname in EXCLUDE_SELECT_OPTIONS:
					continue

				select_options = [option for option in message.split("\n") if option and not option.isdigit()]

				if select_options and "icon" in select_options[0]:
					continue

				messages.extend(
					(
						option,
						f"Option for the '{_label}' ({fieldtype}) field in PageType '{pagetype}'",
					)
					for option in select_options
				)
			elif fieldtype == "HTML":
				messages.append(
					(message, f"Content of the '{_label}' ({fieldtype}) field in PageType '{pagetype}'")
				)

	for link in links:
		if group := link.get("group"):
			messages.append((group, f"Group in {pagetype}'s connections"))

		if link_pagetype := link.get("link_pagetype"):
			messages.append((link_pagetype, f"Linked PageType in {pagetype}'s connections"))

	# By using "pgettext" as the function name we can supply the pagetype as context
	yield from ((None, "_", message, [comment]) for message, comment in messages)

	# Role names do not get context because they are used with multiple pagetypes
	yield from (
		(None, "_", perm["role"], ["Name of a role"])
		for perm in data.get("permissions", [])
		if "role" in perm
	)
