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

import jingrow
from jingrow.model.page import Page


class ListViewSettings(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

		allow_edit: DF.Check
		disable_auto_refresh: DF.Check
		disable_automatic_recency_filters: DF.Check
		disable_comment_count: DF.Check
		disable_count: DF.Check
		disable_sidebar_stats: DF.Check
		fields: DF.Code | None
		total_fields: DF.Literal["", "4", "5", "6", "7", "8", "9", "10"]
	# end: auto-generated types
	pass


@jingrow.whitelist()
def save_listview_settings(pagetype, listview_settings, removed_listview_fields):
	listview_settings = jingrow.parse_json(listview_settings)
	removed_listview_fields = jingrow.parse_json(removed_listview_fields)

	if jingrow.get_all("List View Settings", filters={"name": pagetype}):
		pg = jingrow.get_pg("List View Settings", pagetype)
		pg.update(listview_settings)
		pg.save()
	else:
		pg = jingrow.new_pg("List View Settings")
		pg.name = pagetype
		pg.update(listview_settings)
		pg.insert()

	set_listview_fields(pagetype, listview_settings.get("fields"), removed_listview_fields)

	return {"meta": jingrow.get_meta(pagetype, False), "listview_settings": pg}


def set_listview_fields(pagetype, listview_fields, removed_listview_fields):
	meta = jingrow.get_meta(pagetype)

	listview_fields = [f.get("fieldname") for f in jingrow.parse_json(listview_fields) if f.get("fieldname")]

	for field in removed_listview_fields:
		set_in_list_view_property(pagetype, meta.get_field(field), "0")

	for field in listview_fields:
		set_in_list_view_property(pagetype, meta.get_field(field), "1")


def set_in_list_view_property(pagetype, field, value):
	if not field or field.fieldname == "status_field":
		return

	property_setter = jingrow.db.get_value(
		"Property Setter",
		{"pg_type": pagetype, "field_name": field.fieldname, "property": "in_list_view"},
	)
	if property_setter:
		pg = jingrow.get_pg("Property Setter", property_setter)
		pg.value = value
		pg.save()
	else:
		jingrow.make_property_setter(
			{
				"pagetype": pagetype,
				"pagetype_or_field": "PageField",
				"fieldname": field.fieldname,
				"property": "in_list_view",
				"value": value,
				"property_type": "Check",
			},
			ignore_validate=True,
		)


@jingrow.whitelist()
def get_default_listview_fields(pagetype):
	meta = jingrow.get_meta(pagetype)
	path = jingrow.get_module_path(
		jingrow.scrub(meta.module), "pagetype", jingrow.scrub(meta.name), jingrow.scrub(meta.name) + ".json"
	)
	pagetype_json = jingrow.get_file_json(path)

	fields = [f.get("fieldname") for f in pagetype_json.get("fields") if f.get("in_list_view")]

	if meta.title_field:
		if meta.title_field.strip() not in fields:
			fields.append(meta.title_field.strip())

	return fields
