# Copyright (c) 2022, JINGROW
# License: MIT. See LICENSE

import jingrow
from jingrow.deferred_insert import deferred_insert as _deferred_insert
from jingrow.model.page import Page


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

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

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

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


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

	_deferred_insert("Route History", routes)


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