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

"""
Create a new document with defaults set
"""

import copy

import jingrow
import jingrow.defaults
from jingrow.core.pagetype.user_permission.user_permission import get_user_permissions
from jingrow.model import data_fieldtypes
from jingrow.permissions import filter_allowed_pgs_for_pagetype
from jingrow.utils import cstr, now_datetime, nowdate, nowtime


def get_new_pg(pagetype, parent_pg=None, parentfield=None, as_dict=False):
	if pagetype not in jingrow.local.new_pg_templates:
		# cache a copy of new pg as it is called
		# frequently for inserts
		jingrow.local.new_pg_templates[pagetype] = make_new_pg(pagetype)

	pg = copy.deepcopy(jingrow.local.new_pg_templates[pagetype])

	set_dynamic_default_values(pg, parent_pg, parentfield)

	if as_dict:
		return pg
	else:
		return jingrow.get_pg(pg)


def make_new_pg(pagetype):
	pg = jingrow.get_pg({"pagetype": pagetype, "__islocal": 1, "owner": jingrow.session.user, "pagestatus": 0})

	set_user_and_static_default_values(pg)

	pg._fix_numeric_types()
	pg = pg.get_valid_dict(sanitize=False)
	pg["pagetype"] = pagetype
	pg["__islocal"] = 1

	if not jingrow.model.meta.is_single(pagetype):
		pg["__unsaved"] = 1

	return pg


def set_user_and_static_default_values(pg):
	user_permissions = get_user_permissions()
	defaults = jingrow.defaults.get_defaults()

	for df in pg.meta.get("fields"):
		if df.fieldtype in data_fieldtypes:
			# user permissions for link options
			pagetype_user_permissions = user_permissions.get(df.options, [])
			# Allowed records for the reference pagetype (link field) along with default pg
			allowed_records, default_pg = filter_allowed_pgs_for_pagetype(
				pagetype_user_permissions, df.parent, with_default_pg=True
			)

			user_default_value = get_user_default_value(
				df, defaults, pagetype_user_permissions, allowed_records, default_pg
			)
			if user_default_value is not None:
				# if fieldtype is link check if pg exists
				if not df.fieldtype == "Link" or jingrow.db.exists(df.options, user_default_value):
					pg.set(df.fieldname, user_default_value)

			else:
				if df.fieldname != pg.meta.title_field:
					static_default_value = get_static_default_value(
						df, pagetype_user_permissions, allowed_records
					)
					if static_default_value is not None:
						pg.set(df.fieldname, static_default_value)


def get_user_default_value(df, defaults, pagetype_user_permissions, allowed_records, default_pg):
	# don't set defaults for "User" link field using User Permissions!
	if df.fieldtype == "Link" and df.options != "User":
		# If user permission has Is Default enabled or single-user permission has found against respective pagetype.
		if not df.ignore_user_permissions and default_pg:
			return default_pg

		# 2 - Look in user defaults
		user_default = defaults.get(df.fieldname)

		allowed_by_user_permission = validate_value_via_user_permissions(
			df, pagetype_user_permissions, allowed_records, user_default=user_default
		)

		# is this user default also allowed as per user permissions?
		if user_default and allowed_by_user_permission:
			return user_default


def get_static_default_value(df, pagetype_user_permissions, allowed_records):
	# 3 - look in default of pagefield
	if df.get("default"):
		if df.default == "__user":
			return jingrow.session.user

		elif df.default == "Today":
			return nowdate()

		elif not cstr(df.default).startswith(":"):
			# a simple default value
			is_allowed_default_value = validate_value_via_user_permissions(
				df, pagetype_user_permissions, allowed_records
			)

			if df.fieldtype != "Link" or df.options == "User" or is_allowed_default_value:
				return df.default

	elif df.fieldtype == "Select" and df.options and df.options not in ("[Select]", "Loading..."):
		return df.options.split("\n", 1)[0]


def validate_value_via_user_permissions(df, pagetype_user_permissions, allowed_records, user_default=None):
	is_valid = True
	# If User Permission exists and allowed records is empty,
	# that means there are User Perms, but none applicable to this new pagetype.

	if user_permissions_exist(df, pagetype_user_permissions) and allowed_records:
		# If allowed records is not empty,
		# check if this field value is allowed via User Permissions applied to this pagetype.
		value = user_default if user_default else df.default
		is_valid = value in allowed_records

	return is_valid


def set_dynamic_default_values(pg, parent_pg, parentfield):
	# these values should not be cached
	user_permissions = get_user_permissions()

	for df in jingrow.get_meta(pg["pagetype"]).get("fields"):
		if df.get("default"):
			if cstr(df.default).startswith(":"):
				default_value = get_default_based_on_another_field(df, user_permissions, parent_pg)
				if default_value is not None and not pg.get(df.fieldname):
					pg[df.fieldname] = default_value

			elif df.fieldtype == "Datetime" and df.default.lower() == "now":
				pg[df.fieldname] = now_datetime()

		if df.fieldtype == "Time":
			pg[df.fieldname] = nowtime()

	if parent_pg:
		pg["parent"] = parent_pg.name
		pg["parenttype"] = parent_pg.pagetype

	if parentfield:
		pg["parentfield"] = parentfield


def user_permissions_exist(df, pagetype_user_permissions):
	return (
		df.fieldtype == "Link"
		and not getattr(df, "ignore_user_permissions", False)
		and pagetype_user_permissions
	)


def get_default_based_on_another_field(df, user_permissions, parent_pg):
	# default value based on another document
	from jingrow.permissions import get_allowed_pgs_for_pagetype

	ref_pagetype = df.default[1:]
	ref_fieldname = ref_pagetype.lower().replace(" ", "_")
	reference_name = parent_pg.get(ref_fieldname) if parent_pg else jingrow.db.get_default(ref_fieldname)
	default_value = jingrow.db.get_value(ref_pagetype, reference_name, df.fieldname)
	is_allowed_default_value = not user_permissions_exist(df, user_permissions.get(df.options)) or (
		default_value in get_allowed_pgs_for_pagetype(user_permissions[df.options], df.parent)
	)

	# is this allowed as per user permissions
	if is_allowed_default_value:
		return default_value
