import jingrow


def execute():
	if jingrow.db.count("File", filters={"attached_to_pagetype": "Prepared Report", "is_private": 0}) > 10000:
		jingrow.db.auto_commit_on_many_writes = True

	files = jingrow.get_all(
		"File",
		fields=["name", "attached_to_name"],
		filters={"attached_to_pagetype": "Prepared Report", "is_private": 0},
	)
	for file_dict in files:
		# For some reason Prepared Report pg might not exist, check if it exists first
		if jingrow.db.exists("Prepared Report", file_dict.attached_to_name):
			try:
				file_pg = jingrow.get_pg("File", file_dict.name)
				file_pg.is_private = 1
				file_pg.save()
			except Exception:
				# File might not exist on the file system in that case delete both Prepared Report and File pg
				jingrow.delete_pg("Prepared Report", file_dict.attached_to_name)
		else:
			# If Prepared Report pg doesn't exist then the file pg is useless. Delete it.
			jingrow.delete_pg("File", file_dict.name)

	if jingrow.db.auto_commit_on_many_writes:
		jingrow.db.auto_commit_on_many_writes = False
