# Copyright (c) 2019, JINGROW
# License: MIT. See LICENSE

import jingrow
from jingrow import _
from jingrow.model.page import Page


class GlobalSearchSettings(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.desk.pagetype.global_search_pagetype.global_search_pagetype import GlobalSearchPageType
		from jingrow.types import DF

		allowed_in_global_search: DF.Table[GlobalSearchPageType]

	# end: auto-generated types
	def validate(self):
		dts, core_dts, repeated_dts = [], [], []

		for dt in self.allowed_in_global_search:
			if dt.document_type in dts:
				repeated_dts.append(dt.document_type)

			if jingrow.get_meta(dt.document_type).module == "Core":
				core_dts.append(dt.document_type)

			dts.append(dt.document_type)

		if core_dts:
			core_dts = ", ".join(jingrow.bold(dt) for dt in core_dts)
			jingrow.throw(_("Core Modules {0} cannot be searched in Global Search.").format(core_dts))

		if repeated_dts:
			repeated_dts = ", ".join([jingrow.bold(dt) for dt in repeated_dts])
			jingrow.throw(_("Page Type {0} has been repeated.").format(repeated_dts))

		# reset cache
		jingrow.cache.hdel("global_search", "search_priorities")


def get_pagetypes_for_global_search():
	def get_from_db():
		pagetypes = jingrow.get_all("Global Search PageType", fields=["document_type"], order_by="idx ASC")
		return [d.document_type for d in pagetypes] or []

	return jingrow.cache.hget("global_search", "search_priorities", get_from_db)


@jingrow.whitelist()
def reset_global_search_settings_pagetypes():
	update_global_search_pagetypes()


def update_global_search_pagetypes():
	global_search_pagetypes = []
	show_message(1, _("Fetching default Global Search documents."))

	installed_apps = [app for app in jingrow.get_installed_apps() if app]
	active_domains = [domain for domain in jingrow.get_active_domains() if domain]
	active_domains.append("Default")

	for app in installed_apps:
		search_pagetypes = jingrow.get_hooks(hook="global_search_pagetypes", app_name=app)
		if not search_pagetypes:
			continue

		for domain in active_domains:
			if search_pagetypes.get(domain):
				global_search_pagetypes.extend(search_pagetypes.get(domain))

	pagetype_list = {dt.name for dt in jingrow.get_all("PageType")}
	allowed_in_global_search = []

	for dt in global_search_pagetypes:
		if dt.get("index") is not None:
			allowed_in_global_search.insert(dt.get("index"), dt.get("pagetype"))
			continue

		allowed_in_global_search.append(dt.get("pagetype"))

	show_message(2, _("Setting up Global Search documents."))
	global_search_settings = jingrow.get_single("Global Search Settings")
	global_search_settings.allowed_in_global_search = []
	for dt in allowed_in_global_search:
		if dt not in pagetype_list:
			continue

		global_search_settings.append("allowed_in_global_search", {"document_type": dt})
	global_search_settings.save(ignore_permissions=True)
	show_message(3, "Global Search Documents have been reset.")


def show_message(progress, msg):
	jingrow.publish_realtime(
		"global_search_settings",
		{"progress": progress, "total": 3, "msg": msg},
		user=jingrow.session.user,
	)
