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

import json

import jingrow
from jingrow import _


@jingrow.whitelist()
def update_event(args, field_map):
	"""Updates Event (called via calendar) based on passed `field_map`"""
	args = jingrow._dict(json.loads(args))
	field_map = jingrow._dict(json.loads(field_map))
	w = jingrow.get_pg(args.pagetype, args.name)
	w.set(field_map.start, args[field_map.start])
	w.set(field_map.end, args.get(field_map.end))
	w.save()


def get_event_conditions(pagetype, filters=None):
	"""Returns SQL conditions with user permissions and filters for event queries"""
	from jingrow.desk.reportview import get_filters_cond

	if not jingrow.has_permission(pagetype):
		jingrow.throw(_("Not Permitted"), jingrow.PermissionError)

	return get_filters_cond(pagetype, filters, [], with_match_conditions=True)


@jingrow.whitelist()
def get_events(pagetype, start, end, field_map, filters=None, fields=None):
	field_map = jingrow._dict(json.loads(field_map))
	fields = jingrow.parse_json(fields)

	pg_meta = jingrow.get_meta(pagetype)
	for d in pg_meta.fields:
		if d.fieldtype == "Color":
			field_map.update({"color": d.fieldname})

	filters = json.loads(filters) if filters else []

	if not fields:
		fields = [field_map.start, field_map.end, field_map.title, "name"]

	if field_map.color:
		fields.append(field_map.color)

	start_date = "ifnull(%s, '0001-01-01 00:00:00')" % field_map.start
	end_date = "ifnull(%s, '2199-12-31 00:00:00')" % field_map.end

	filters += [
		[pagetype, start_date, "<=", end],
		[pagetype, end_date, ">=", start],
	]
	fields = list({field for field in fields if field})
	return jingrow.get_list(pagetype, fields=fields, filters=filters)
