import json

import jingrow
from jingrow import _


def execute():
	for seq, workspace in enumerate(jingrow.get_all("Workspace")):
		pg = jingrow.get_pg("Workspace", workspace.name)
		content = create_content(pg)
		update_workspace(pg, seq, content)


def create_content(pg):
	content = []
	if pg.get("onboarding"):
		content.append({"type": "onboarding", "data": {"onboarding_name": pg.onboarding, "col": 12}})
	if pg.charts:
		invalid_links = []
		for c in pg.charts:
			if c.get_invalid_links()[0]:
				invalid_links.append(c)
			else:
				content.append({"type": "chart", "data": {"chart_name": c.label, "col": 12}})
		for l in invalid_links:
			del pg.charts[pg.charts.index(l)]
	if pg.shortcuts:
		invalid_links = []
		if pg.charts:
			content.append({"type": "spacer", "data": {"col": 12}})
		content.append(
			{
				"type": "header",
				"data": {"text": pg.get("shortcuts_label") or _("Your Shortcuts"), "level": 4, "col": 12},
			}
		)
		for s in pg.shortcuts:
			if s.get_invalid_links()[0]:
				invalid_links.append(s)
			else:
				content.append({"type": "shortcut", "data": {"shortcut_name": s.label, "col": 4}})
		for l in invalid_links:
			del pg.shortcuts[pg.shortcuts.index(l)]
	if pg.links:
		invalid_links = []
		content.append({"type": "spacer", "data": {"col": 12}})
		content.append(
			{
				"type": "header",
				"data": {"text": pg.get("cards_label") or _("Reports & Masters"), "level": 4, "col": 12},
			}
		)
		for l in pg.links:
			if l.type == "Card Break":
				content.append({"type": "card", "data": {"card_name": l.label, "col": 4}})
			if l.get_invalid_links()[0]:
				invalid_links.append(l)
		for l in invalid_links:
			del pg.links[pg.links.index(l)]
	return content


def update_workspace(pg, seq, content):
	if (
		not pg.title
		and (not pg.content or pg.content == "[]")
		and not pg.get("is_standard")
		and not pg.public
	):
		pg.sequence_id = seq + 1
		pg.content = json.dumps(content)
		pg.public = 0 if pg.for_user else 1
		pg.title = pg.get("extends") or pg.get("label")
		pg.extends = ""
		pg.category = ""
		pg.onboarding = ""
		pg.extends_another_page = 0
		pg.is_default = 0
		pg.is_standard = 0
		pg.developer_mode_only = 0
		pg.disable_user_customization = 0
		pg.pin_to_top = 0
		pg.pin_to_bottom = 0
		pg.hide_custom = 0
		pg.save(ignore_permissions=True)
