# Copyright (c) 2022, JINGROW and Contributors
# License: MIT. See LICENSE
"""
	Utilities for using modules
"""
import json
import os
from textwrap import dedent, indent
from typing import TYPE_CHECKING, Union

import jingrow
from jingrow import _, get_module_path, scrub
from jingrow.utils import cint, cstr, now_datetime

if TYPE_CHECKING:
	from types import ModuleType

	from jingrow.model.page import Page


pagetype_python_modules = {}


def export_module_json(pg: "Page", is_standard: bool, module: str) -> str | None:
	"""Make a folder for the given pg and add its json file (make it a standard
	object that will be synced)

	Returns the absolute file_path without the extension.
	Eg: For exporting a Print Format "_Test Print Format 1", the return value will be
	`/home/gavin/jingrow-bench/apps/jingrow/jingrow/core/print_format/_test_print_format_1/_test_print_format_1`
	"""
	if not jingrow.flags.in_import and is_standard and jingrow.conf.developer_mode:
		from jingrow.modules.export_file import export_to_files

		# json
		export_to_files(record_list=[[pg.pagetype, pg.name]], record_module=module, create_init=is_standard)

		return os.path.join(
			jingrow.get_module_path(module), scrub(pg.pagetype), scrub(pg.name), scrub(pg.name)
		)


def get_pg_module(module: str, pagetype: str, name: str) -> "ModuleType":
	"""Get custom module for given document"""
	module_name = "{app}.{module}.{pagetype}.{name}.{name}".format(
		app=jingrow.local.module_app[scrub(module)],
		pagetype=scrub(pagetype),
		module=scrub(module),
		name=scrub(name),
	)
	return jingrow.get_module(module_name)


@jingrow.whitelist()
def export_customizations(
	module: str, pagetype: str, sync_on_migrate: bool = False, with_permissions: bool = False
):
	"""Export Custom Field and Property Setter for the current document to the app folder.
	This will be synced with bench migrate"""

	sync_on_migrate = cint(sync_on_migrate)
	with_permissions = cint(with_permissions)

	if not jingrow.conf.developer_mode:
		jingrow.throw(_("Only allowed to export customizations in developer mode"))

	custom = {
		"custom_fields": jingrow.get_all("Custom Field", fields="*", filters={"dt": pagetype}, order_by="name"),
		"property_setters": jingrow.get_all(
			"Property Setter", fields="*", filters={"pg_type": pagetype}, order_by="name"
		),
		"custom_perms": [],
		"links": jingrow.get_all("PageType Link", fields="*", filters={"parent": pagetype}, order_by="name"),
		"pagetype": pagetype,
		"sync_on_migrate": sync_on_migrate,
	}

	if with_permissions:
		custom["custom_perms"] = jingrow.get_all(
			"Custom PagePerm", fields="*", filters={"parent": pagetype}, order_by="name"
		)

	# also update the custom fields and property setters for all child tables
	for d in jingrow.get_meta(pagetype).get_table_fields():
		export_customizations(module, d.options, sync_on_migrate, with_permissions)

	if custom["custom_fields"] or custom["property_setters"] or custom["custom_perms"]:
		folder_path = os.path.join(get_module_path(module), "custom")
		if not os.path.exists(folder_path):
			os.makedirs(folder_path)

		path = os.path.join(folder_path, scrub(pagetype) + ".json")
		with open(path, "w") as f:
			f.write(jingrow.as_json(custom))

		jingrow.msgprint(_("Customizations for <b>{0}</b> exported to:<br>{1}").format(pagetype, path))
		return path


def sync_customizations(app=None):
	"""Sync custom fields and property setters from custom folder in each app module"""

	if app:
		apps = [app]
	else:
		apps = jingrow.get_installed_apps()

	for app_name in apps:
		for module_name in jingrow.local.app_modules.get(app_name) or []:
			folder = jingrow.get_app_path(app_name, module_name, "custom")
			if os.path.exists(folder):
				for fname in os.listdir(folder):
					if fname.endswith(".json"):
						with open(os.path.join(folder, fname)) as f:
							data = json.loads(f.read())
						if data.get("sync_on_migrate"):
							sync_customizations_for_pagetype(data, folder, fname)
						elif jingrow.flags.in_install and app:
							sync_customizations_for_pagetype(data, folder, fname)


def sync_customizations_for_pagetype(data: dict, folder: str, filename: str = ""):
	"""Sync pagetype customzations for a particular data set"""
	from jingrow.core.pagetype.pagetype.pagetype import validate_fields_for_pagetype

	pagetype = data["pagetype"]
	update_schema = False

	def sync(key, custom_pagetype, pagetype_fieldname):
		pagetypes = list(set(map(lambda row: row.get(pagetype_fieldname), data[key])))

		# sync single pagetype exculding the child pagetype
		def sync_single_pagetype(pg_type):
			def _insert(data):
				if data.get(pagetype_fieldname) == pg_type:
					data["pagetype"] = custom_pagetype
					pg = jingrow.get_pg(data)
					pg.db_insert()

			match custom_pagetype:
				case "Custom Field":
					for d in data[key]:
						field = jingrow.db.get_value(
							"Custom Field", {"dt": pg_type, "fieldname": d["fieldname"]}
						)
						if not field:
							d["owner"] = "Administrator"
							_insert(d)
						else:
							custom_field = jingrow.get_pg("Custom Field", field)
							custom_field.flags.ignore_validate = True
							custom_field.update(d)
							custom_field.db_update()
				case "Property Setter":
					# Property setter implement their own deduplication, we can just sync them as is
					for d in data[key]:
						if d.get("pg_type") == pg_type:
							d["pagetype"] = "Property Setter"
							pg = jingrow.get_pg(d)
							pg.flags.validate_fields_for_pagetype = False
							pg.insert()
				case "Custom PagePerm":
					# TODO/XXX: PagePerm have no "sync" as of now. They get OVERRIDDEN on sync.
					jingrow.db.delete("Custom PagePerm", {"parent": pg_type})

					for d in data[key]:
						_insert(d)

		for pg_type in pagetypes:
			# only sync the parent pagetype and child pagetype if there isn't any other child table json file
			if pg_type == pagetype or not os.path.exists(os.path.join(folder, scrub(pg_type) + ".json")):
				sync_single_pagetype(pg_type)

	if not jingrow.db.exists("PageType", pagetype):
		print(_("PageType {0} does not exist.").format(pagetype))
		print(_("Skipping fixture syncing for pagetype {0} from file {1}").format(pagetype, filename))
		return

	if data["custom_fields"]:
		sync("custom_fields", "Custom Field", "dt")
		update_schema = True

	if data["property_setters"]:
		sync("property_setters", "Property Setter", "pg_type")

	print(f"Updating customizations for {pagetype}")
	if data.get("custom_perms"):
		sync("custom_perms", "Custom PagePerm", "parent")

	validate_fields_for_pagetype(pagetype)

	if update_schema and not jingrow.db.get_value("PageType", pagetype, "issingle"):
		jingrow.db.updatedb(pagetype)


def scrub_dt_dn(dt: str, dn: str) -> tuple[str, str]:
	"""Returns in lowercase and code friendly names of pagetype and name for certain types"""
	return scrub(dt), scrub(dn)


def get_pg_path(module: str, pagetype: str, name: str) -> str:
	"""Returns path of a pg in a module"""
	return os.path.join(get_module_path(module), *scrub_dt_dn(pagetype, name))


def reload_pg(
	module: str,
	dt: str | None = None,
	dn: str | None = None,
	force: bool = False,
	reset_permissions: bool = False,
):
	"""Reload Page from model (`[module]/<pagetype>/[name]/[name].json`) files"""
	from jingrow.modules.import_file import import_files

	return import_files(module, dt, dn, force=force, reset_permissions=reset_permissions)


def export_pg(pagetype, name, module=None):
	"""Write a pg to standard path."""
	from jingrow.modules.export_file import write_document_file

	print(f"Exporting Page {pagetype} {name}")
	module = module or jingrow.db.get_value("PageType", name, "module")
	write_document_file(jingrow.get_pg(pagetype, name), module)


def get_pagetype_module(pagetype: str) -> str:
	"""Returns **Module Def** name of given pagetype."""
	pagetype_module_map = jingrow.cache.get_value(
		"pagetype_modules",
		generator=lambda: dict(jingrow.qb.from_("PageType").select("name", "module").run()),
	)

	if module_name := pagetype_module_map.get(pagetype):
		return module_name
	else:
		jingrow.throw(_("PageType {} not found").format(pagetype), exc=jingrow.DoesNotExistError)


def load_pagetype_module(pagetype, module=None, prefix="", suffix=""):
	"""Returns the module object for given pagetype.

	Note: This will return the standard defined module object for the pagetype irrespective
	of the `override_pagetype_class` hook.
	"""
	module = module or get_pagetype_module(pagetype)
	app = get_module_app(module)
	key = (app, pagetype, prefix, suffix)
	module_name = get_module_name(pagetype, module, prefix, suffix)

	if key not in pagetype_python_modules:
		try:
			pagetype_python_modules[key] = jingrow.get_module(module_name)
		except ImportError as e:
			msg = f"Module import failed for {pagetype}, the PageType you're trying to open might be deleted."
			msg += f"\nError: {e}"
			raise ImportError(msg) from e

	return pagetype_python_modules[key]


def get_module_name(pagetype: str, module: str, prefix: str = "", suffix: str = "", app: str | None = None):
	app = scrub(app or get_module_app(module))
	module = scrub(module)
	pagetype = scrub(pagetype)
	return f"{app}.{module}.pagetype.{pagetype}.{prefix}{pagetype}{suffix}"


def get_module_app(module: str) -> str:
	app = jingrow.local.module_app.get(scrub(module))
	if app is None:
		jingrow.throw(_("Module {} not found").format(module), exc=jingrow.DoesNotExistError)
	return app


def get_app_publisher(module: str) -> str:
	app = get_module_app(module)
	if not app:
		jingrow.throw(_("App not found for module: {0}").format(module))
	return jingrow.get_hooks(hook="app_publisher", app_name=app)[0]


def make_boilerplate(
	template: str, pg: Union["Page", "jingrow._dict"], opts: Union[dict, "jingrow._dict"] = None
):
	target_path = get_pg_path(pg.module, pg.pagetype, pg.name)
	template_name = template.replace("controller", scrub(pg.name))
	if template_name.endswith("._py"):
		template_name = template_name[:-4] + ".py"
	target_file_path = os.path.join(target_path, template_name)
	template_file_path = os.path.join(
		get_module_path("core"), "pagetype", scrub(pg.pagetype), "boilerplate", template
	)

	if os.path.exists(target_file_path):
		print(f"{target_file_path} already exists, skipping...")
		return

	pg = pg or jingrow._dict()
	opts = opts or jingrow._dict()
	app_publisher = get_app_publisher(pg.module)
	base_class = "Page"
	base_class_import = "from jingrow.model.page import Page"
	controller_body = "pass"

	if pg.get("is_tree"):
		base_class = "NestedSet"
		base_class_import = "from jingrow.utils.nestedset import NestedSet"

	if pg.get("is_virtual"):
		controller_body = indent(
			dedent(
				"""
			def db_insert(self, *args, **kwargs):
				pass

			def load_from_db(self):
				pass

			def db_update(self):
				pass

			@staticmethod
			def get_list(args):
				pass

			@staticmethod
			def get_count(args):
				pass

			@staticmethod
			def get_stats(args):
				pass
			"""
			),
			"\t",
		)

	with open(target_file_path, "w") as target, open(template_file_path) as source:
		template = source.read()
		controller_file_content = cstr(template).format(
			app_publisher=app_publisher,
			year=now_datetime().year,
			classname=pg.name.replace(" ", "").replace("-", ""),
			base_class_import=base_class_import,
			base_class=base_class,
			pagetype=pg.name,
			**opts,
			custom_controller=controller_body,
		)
		target.write(jingrow.as_unicode(controller_file_content))
