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

import jingrow
from jingrow.core.pagetype.report.report import is_prepared_report_enabled
from jingrow.model.page import Page
from jingrow.permissions import ALL_USER_ROLE
from jingrow.utils import cint


class RolePermissionforPageandReport(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.core.pagetype.has_role.has_role import HasRole
		from jingrow.types import DF

		enable_prepared_report: DF.Check
		page: DF.Link | None
		report: DF.Link | None
		roles: DF.Table[HasRole]
		set_role_for: DF.Literal["", "Page", "Report"]

	# end: auto-generated types
	@jingrow.whitelist()
	def set_report_page_data(self):
		self.set_custom_roles()
		self.check_prepared_report_disabled()

	def set_custom_roles(self):
		args = self.get_args()
		self.set("roles", [])

		name = jingrow.db.get_value("Custom Role", args, "name")
		if name:
			pg = jingrow.get_pg("Custom Role", name)
			roles = pg.roles
		else:
			roles = self.get_standard_roles()

		self.set("roles", roles)

	def check_prepared_report_disabled(self):
		if self.report:
			self.enable_prepared_report = is_prepared_report_enabled(self.report)

	def get_standard_roles(self):
		pagetype = self.set_role_for
		pagename = self.page if self.set_role_for == "Page" else self.report
		pg = jingrow.get_pg(pagetype, pagename)
		return pg.roles

	@jingrow.whitelist()
	def reset_roles(self):
		roles = self.get_standard_roles()
		self.set("roles", roles)
		self.update_custom_roles()
		self.update_disable_prepared_report()

	@jingrow.whitelist()
	def update_report_page_data(self):
		self.update_custom_roles()
		self.update_disable_prepared_report()

	def update_custom_roles(self):
		args = self.get_args()
		name = jingrow.db.get_value("Custom Role", args, "name")

		args.update({"pagetype": "Custom Role", "roles": self.get_roles()})

		if self.report:
			args.update({"ref_pagetype": jingrow.db.get_value("Report", self.report, "ref_pagetype")})

		if name:
			custom_role = jingrow.get_pg("Custom Role", name)
			custom_role.set("roles", self.get_roles())
			custom_role.save()
		else:
			jingrow.get_pg(args).insert()

	def update_disable_prepared_report(self):
		if self.report:
			# intentionally written update query in jingrow.db.sql instead of jingrow.db.set_value
			jingrow.db.sql(
				"""update `tabReport` set prepared_report = %s
				where name = %s""",
				(self.enable_prepared_report, self.report),
			)

	def get_args(self, row=None):
		name = self.page if self.set_role_for == "Page" else self.report
		check_for_field = self.set_role_for.replace(" ", "_").lower()

		return {check_for_field: name}

	def get_roles(self):
		return [
			{"role": data.role, "parenttype": "Custom Role"}
			for data in self.roles
			if data.role != ALL_USER_ROLE
		]

	def update_status(self):
		return jingrow.render_template
