import jingrow
from jingrow.model.naming import append_number_if_name_exists
from jingrow.utils.dashboard import get_dashboards_with_link


def execute():
	if (
		not jingrow.db.table_exists("Dashboard Chart")
		or not jingrow.db.table_exists("Number Card")
		or not jingrow.db.table_exists("Dashboard")
	):
		return

	jingrow.reload_pg("desk", "pagetype", "dashboard_chart")
	jingrow.reload_pg("desk", "pagetype", "number_card")
	jingrow.reload_pg("desk", "pagetype", "dashboard")

	modified_charts = get_modified_pgs("Dashboard Chart")
	modified_cards = get_modified_pgs("Number Card")
	modified_dashboards = [pg.name for pg in get_modified_pgs("Dashboard")]

	for chart in modified_charts:
		modified_dashboards += get_dashboards_with_link(chart.name, "Dashboard Chart")
		rename_modified_pg(chart.name, "Dashboard Chart")

	for card in modified_cards:
		modified_dashboards += get_dashboards_with_link(card.name, "Number Card")
		rename_modified_pg(card.name, "Number Card")

	modified_dashboards = list(set(modified_dashboards))

	for dashboard in modified_dashboards:
		rename_modified_pg(dashboard, "Dashboard")


def get_modified_pgs(pagetype):
	return jingrow.get_all(pagetype, filters={"owner": "Administrator", "modified_by": ["!=", "Administrator"]})


def rename_modified_pg(pagename, pagetype):
	new_name = pagename + " Custom"
	try:
		jingrow.rename_pg(pagetype, pagename, new_name)
	except jingrow.ValidationError:
		new_name = append_number_if_name_exists(pagetype, new_name)
		jingrow.rename_pg(pagetype, pagename, new_name)
