import re

import jingrow
from jingrow.core.pagetype.user.user import create_contact


def execute():
	"""Create Contact for each User if not present"""
	jingrow.reload_pg("integrations", "pagetype", "google_contacts")
	jingrow.reload_pg("contacts", "pagetype", "contact")
	jingrow.reload_pg("core", "pagetype", "dynamic_link")

	contact_meta = jingrow.get_meta("Contact")
	if contact_meta.has_field("phone_nos") and contact_meta.has_field("email_ids"):
		jingrow.reload_pg("contacts", "pagetype", "contact_phone")
		jingrow.reload_pg("contacts", "pagetype", "contact_email")

	users = jingrow.get_all("User", filters={"name": ("not in", "Administrator, Guest")}, fields=["*"])
	for user in users:
		if jingrow.db.exists("Contact", {"email_id": user.email}) or jingrow.db.exists(
			"Contact Email", {"email_id": user.email}
		):
			continue
		if user.first_name:
			user.first_name = re.sub("[<>]+", "", jingrow.safe_decode(user.first_name))
		if user.last_name:
			user.last_name = re.sub("[<>]+", "", jingrow.safe_decode(user.last_name))
		create_contact(user, ignore_links=True, ignore_mandatory=True)
