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

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


class RouteHistory(Document):
	@staticmethod
	def clear_old_logs(days=30):
		from influxframework.query_builder import Interval
		from influxframework.query_builder.functions import Now

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


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

	_deferred_insert("Route History", routes)


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