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

from collections import defaultdict

import jingrow

ignore_pagetypes = {
	"PageType",
	"Print Format",
	"Role",
	"Module Def",
	"Communication",
	"ToDo",
	"Version",
	"Error Log",
	"Scheduled Job Log",
	"Event Sync Log",
	"Event Update Log",
	"Access Log",
	"View Log",
	"System Log",
	"Energy Point Log",
	"Notification Log",
	"Email Queue",
	"PageShare",
	"Page Follow",
	"Console Log",
	"User",
}


def notify_link_count(pagetype, name):
	"""updates link count for given document"""

	if pagetype in ignore_pagetypes or not jingrow.request:
		return

	if not hasattr(jingrow.local, "_link_count"):
		jingrow.local._link_count = defaultdict(int)
		jingrow.db.after_commit.add(flush_local_link_count)

	jingrow.local._link_count[(pagetype, name)] += 1


def flush_local_link_count():
	"""flush from local before ending request"""
	new_links = getattr(jingrow.local, "_link_count", None)
	if not new_links:
		return

	link_count = jingrow.cache.get_value("_link_count") or {}

	for key, value in new_links.items():
		if key in link_count:
			link_count[key] += value
		else:
			link_count[key] = value

	jingrow.cache.set_value("_link_count", link_count)
	new_links.clear()


def update_link_count():
	"""increment link count in the `idx` column for the given document"""
	link_count = jingrow.cache.get_value("_link_count")

	if link_count:
		for (pagetype, name), count in link_count.items():
			try:
				table = jingrow.qb.PageType(pagetype)
				jingrow.qb.update(table).set(table.idx, table.idx + count).where(table.name == name).run()
				jingrow.db.commit()
			except Exception as e:
				if not jingrow.db.is_table_missing(e):  # table not found, single
					raise e
	# reset the count
	jingrow.cache.delete_value("_link_count")
