# Copyright (c) 2022, XhiveFramework Technologies and contributors
# License: MIT. See LICENSE

import xhiveframework
from xhiveframework.deferred_insert import deferred_insert as _deferred_insert
from xhiveframework.model.document import Document


class RouteHistory(Document):
	# 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 xhiveframework.types import DF

		route: DF.Data | None
		user: DF.Link | None
	# end: auto-generated types

	@staticmethod
	def clear_old_logs(days=30):
		from xhiveframework.query_builder import Interval
		from xhiveframework.query_builder.functions import Now

		table = xhiveframework.qb.DocType("Route History")
		xhiveframework.db.delete(table, filters=(table.modified < (Now() - Interval(days=days))))


@xhiveframework.whitelist()
def deferred_insert(routes):
	routes = [
		{
			"user": xhiveframework.session.user,
			"route": route.get("route"),
			"creation": route.get("creation"),
		}
		for route in xhiveframework.parse_json(routes)
	]

	_deferred_insert("Route History", routes)


@xhiveframework.whitelist()
def frequently_visited_links():
	return xhiveframework.get_all(
		"Route History",
		fields=["route", "count(name) as count"],
		filters={"user": xhiveframework.session.user},
		group_by="route",
		order_by="count desc",
		limit=5,
	)
