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

import jingrow
import jingrow.utils.user
from jingrow.model import data_fieldtypes
from jingrow.permissions import rights


def execute(filters=None):
	jingrow.only_for("System Manager")

	user, pagetype, show_permissions = (
		filters.get("user"),
		filters.get("pagetype"),
		filters.get("show_permissions"),
	)

	columns, fields = get_columns_and_fields(pagetype)
	data = jingrow.get_list(pagetype, fields=fields, as_list=True, user=user)

	if show_permissions:
		columns = columns + [jingrow.unscrub(right) + ":Check:80" for right in rights]
		data = list(data)
		for i, pg in enumerate(data):
			permission = jingrow.permissions.get_pg_permissions(jingrow.get_pg(pagetype, pg[0]), user)
			data[i] = pg + tuple(permission.get(right) for right in rights)

	return columns, data


def get_columns_and_fields(pagetype):
	columns = [f"Name:Link/{pagetype}:200"]
	fields = ["name"]
	for df in jingrow.get_meta(pagetype).fields:
		if df.in_list_view and df.fieldtype in data_fieldtypes:
			fields.append(f"`{df.fieldname}`")
			fieldtype = f"Link/{df.options}" if df.fieldtype == "Link" else df.fieldtype
			columns.append(f"{df.label}:{fieldtype}:{df.width or 100}")

	return columns, fields


@jingrow.whitelist()
@jingrow.validate_and_sanitize_search_inputs
def query_pagetypes(pagetype, txt, searchfield, start, page_len, filters):
	user = filters.get("user")
	user_perms = jingrow.utils.user.UserPermissions(user)
	user_perms.build_permissions()
	can_read = user_perms.can_read  # Does not include child tables
	include_single_pagetypes = filters.get("include_single_pagetypes")

	single_pagetypes = [d[0] for d in jingrow.db.get_values("PageType", {"issingle": 1})]

	return [
		[dt]
		for dt in can_read
		if txt.lower().replace("%", "") in jingrow._(dt).lower()
		and (include_single_pagetypes or dt not in single_pagetypes)
	]
