# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

import jingrow


def sendmail_to_system_managers(subject, content):
	jingrow.sendmail(recipients=get_system_managers(), subject=subject, content=content)


@jingrow.whitelist()
def get_contact_list(txt, page_length=20, extra_filters: str | None = None) -> list[dict]:
	"""Return email ids for a multiselect field."""
	if extra_filters:
		extra_filters = jingrow.parse_json(extra_filters)

	filters = [
		["Contact Email", "email_id", "is", "set"],
	]
	if extra_filters:
		filters.extend(extra_filters)

	fields = ["first_name", "middle_name", "last_name", "company_name"]
	contacts = jingrow.get_list(
		"Contact",
		fields=["full_name", "`tabContact Email`.email_id"],
		filters=filters,
		or_filters=[[field, "like", f"%{txt}%"] for field in fields]
		+ [["Contact Email", "email_id", "like", f"%{txt}%"]],
		limit_page_length=page_length,
	)

	# The multiselect field will store the `label` as the selected value.
	# The `value` is just used as a unique key to distinguish between the options.
	# http://git.jingrow.com/jingrow/jingrow/blob/6c6a89bcdd9454060a1333e23b855d0505c9ebc2/jingrow/public/js/jingrow/form/controls/autocomplete.js#L29-L35
	return [
		jingrow._dict(
			value=d.email_id,
			label=d.email_id,
			description=d.full_name,
		)
		for d in contacts
	]


def get_system_managers():
	return jingrow.db.sql_list(
		"""select parent FROM `tabHas Role`
		WHERE role='System Manager'
		AND parent!='Administrator'
		AND parent IN (SELECT email FROM tabUser WHERE enabled=1)"""
	)


@jingrow.whitelist()
def relink(name, reference_pagetype=None, reference_name=None):
	jingrow.db.sql(
		"""update
			`tabEmail`
		set
			reference_pagetype = %s,
			reference_name = %s,
			status = "Linked"
		where
			name = %s""",
		(reference_pagetype, reference_name, name),
	)


@jingrow.whitelist()
@jingrow.validate_and_sanitize_search_inputs
def get_communication_pagetype(pagetype, txt, searchfield, start, page_len, filters):
	user_perms = jingrow.utils.user.UserPermissions(jingrow.session.user)
	user_perms.build_permissions()
	can_read = user_perms.can_read
	from jingrow.modules import load_pagetype_module

	com_pagetypes = []
	if len(txt) < 2:
		for name in jingrow.get_hooks("communication_pagetypes"):
			try:
				module = load_pagetype_module(name, suffix="_dashboard")
				if hasattr(module, "get_data"):
					for i in module.get_data()["transactions"]:
						com_pagetypes += i["items"]
			except ImportError:
				pass
	else:
		com_pagetypes = [
			d[0] for d in jingrow.db.get_values("PageType", {"issingle": 0, "istable": 0, "hide_toolbar": 0})
		]

	return [[dt] for dt in com_pagetypes if txt.lower().replace("%", "") in dt.lower() and dt in can_read]
