# Copyright (c) 2022, JINGROW and Contributors
# License: MIT. See LICENSE
from contextlib import contextmanager
from datetime import timedelta
from unittest.mock import Mock, patch

import jingrow
from jingrow.app import make_form_dict
from jingrow.core.pagetype.pagetype.test_pagetype import new_pagetype
from jingrow.desk.pagetype.note.note import Note
from jingrow.model.naming import make_autoname, parse_naming_series, revert_series_if_last
from jingrow.tests.utils import JingrowTestCase, timeout
from jingrow.utils import cint, now_datetime, set_request
from jingrow.website.serve import get_response

from . import update_system_settings


class CustomTestNote(Note):
	@property
	def age(self):
		return now_datetime() - self.creation


class CustomNoteWithoutProperty(Note):
	def age(self):
		return now_datetime() - self.creation


class TestDocument(JingrowTestCase):
	def test_get_return_empty_list_for_table_field_if_none(self):
		d = jingrow.get_pg({"pagetype": "User"})
		self.assertEqual(d.get("roles"), [])

	def test_load(self):
		d = jingrow.get_pg("PageType", "User")
		self.assertEqual(d.pagetype, "PageType")
		self.assertEqual(d.name, "User")
		self.assertEqual(d.allow_rename, 1)
		self.assertTrue(isinstance(d.fields, list))
		self.assertTrue(isinstance(d.permissions, list))
		self.assertTrue(filter(lambda d: d.fieldname == "email", d.fields))

	def test_load_single(self):
		d = jingrow.get_pg("Website Settings", "Website Settings")
		self.assertEqual(d.name, "Website Settings")
		self.assertEqual(d.pagetype, "Website Settings")
		self.assertTrue(d.disable_signup in (0, 1))

	def test_insert(self):
		d = jingrow.get_pg(
			{
				"pagetype": "Event",
				"subject": "test-pg-test-event 1",
				"starts_on": "2014-01-01",
				"event_type": "Public",
			}
		)
		d.insert()
		self.assertTrue(d.name.startswith("EV"))
		self.assertEqual(jingrow.db.get_value("Event", d.name, "subject"), "test-pg-test-event 1")

		# test if default values are added
		self.assertEqual(d.send_reminder, 1)
		return d

	def test_website_route_default(self):
		default = jingrow.generate_hash()
		child_table = new_pagetype(default=default, istable=1).insert().name
		parent = (
			new_pagetype(fields=[{"fieldtype": "Table", "options": child_table, "fieldname": "child_table"}])
			.insert()
			.name
		)

		pg = jingrow.get_pg({"pagetype": parent, "child_table": [{"some_fieldname": "xasd"}]}).insert()
		pg.append("child_table", {})
		pg.save()
		self.assertEqual(pg.child_table[-1].some_fieldname, default)

	def test_insert_with_child(self):
		d = jingrow.get_pg(
			{
				"pagetype": "Event",
				"subject": "test-pg-test-event 2",
				"starts_on": "2014-01-01",
				"event_type": "Public",
			}
		)
		d.insert()
		self.assertTrue(d.name.startswith("EV"))
		self.assertEqual(jingrow.db.get_value("Event", d.name, "subject"), "test-pg-test-event 2")

	def test_update(self):
		d = self.test_insert()
		d.subject = "subject changed"
		d.save()

		self.assertEqual(jingrow.db.get_value(d.pagetype, d.name, "subject"), "subject changed")

	def test_value_changed(self):
		d = self.test_insert()
		d.subject = "subject changed again"
		d.load_pg_before_save()
		d.update_modified()

		self.assertTrue(d.has_value_changed("subject"))
		self.assertTrue(d.has_value_changed("modified"))

		self.assertFalse(d.has_value_changed("creation"))
		self.assertFalse(d.has_value_changed("event_type"))

	def test_mandatory(self):
		# TODO: recheck if it is OK to force delete
		jingrow.delete_pg_if_exists("User", "test_mandatory@example.com", 1)

		d = jingrow.get_pg(
			{
				"pagetype": "User",
				"email": "test_mandatory@example.com",
			}
		)
		self.assertRaises(jingrow.MandatoryError, d.insert)

		d.set("first_name", "Test Mandatory")
		d.insert()
		self.assertEqual(jingrow.db.get_value("User", d.name), d.name)

	def test_text_editor_field(self):
		try:
			jingrow.get_pg(pagetype="System Log", subject="test", message='<img src="test.png" />').insert()
		except jingrow.MandatoryError:
			self.fail("Text Editor false positive mandatory error")

	def test_conflict_validation(self):
		d1 = self.test_insert()
		d2 = jingrow.get_pg(d1.pagetype, d1.name)
		d1.save()
		self.assertRaises(jingrow.TimestampMismatchError, d2.save)

	def test_conflict_validation_single(self):
		d1 = jingrow.get_pg("Website Settings", "Website Settings")
		d1.home_page = "test-web-page-1"

		d2 = jingrow.get_pg("Website Settings", "Website Settings")
		d2.home_page = "test-web-page-1"

		d1.save()
		self.assertRaises(jingrow.TimestampMismatchError, d2.save)

	def test_permission(self):
		jingrow.set_user("Guest")
		self.assertRaises(jingrow.PermissionError, self.test_insert)
		jingrow.set_user("Administrator")

	def test_permission_single(self):
		jingrow.set_user("Guest")
		d = jingrow.get_pg("Website Settings", "Website Settings")
		self.assertRaises(jingrow.PermissionError, d.save)
		jingrow.set_user("Administrator")

	def test_link_validation(self):
		jingrow.delete_pg_if_exists("User", "test_link_validation@example.com", 1)

		d = jingrow.get_pg(
			{
				"pagetype": "User",
				"email": "test_link_validation@example.com",
				"first_name": "Link Validation",
				"roles": [{"role": "ABC"}],
			}
		)
		self.assertRaises(jingrow.LinkValidationError, d.insert)

		d.roles = []
		d.append("roles", {"role": "System Manager"})
		d.insert()

		self.assertEqual(jingrow.db.get_value("User", d.name), d.name)

	def test_validate(self):
		d = self.test_insert()
		d.starts_on = "2014-01-01"
		d.ends_on = "2013-01-01"
		self.assertRaises(jingrow.ValidationError, d.validate)
		self.assertRaises(jingrow.ValidationError, d.run_method, "validate")
		self.assertRaises(jingrow.ValidationError, d.save)

	def test_db_set_no_query_on_new_pgs(self):
		user = jingrow.new_pg("User")
		user.db_set("user_type", "Magical Wizard")
		with self.assertQueryCount(0):
			user.db_set("user_type", "Magical Wizard")

	def test_new_pg_with_fields(self):
		user = jingrow.new_pg("User", first_name="wizard")
		self.assertEqual(user.first_name, "wizard")

	def test_update_after_submit(self):
		d = self.test_insert()
		d.starts_on = "2014-09-09"
		self.assertRaises(jingrow.UpdateAfterSubmitError, d.validate_update_after_submit)
		d.meta.get_field("starts_on").allow_on_submit = 1
		d.validate_update_after_submit()
		d.meta.get_field("starts_on").allow_on_submit = 0

		# when comparing date(2014, 1, 1) and "2014-01-01"
		d.reload()
		d.starts_on = "2014-01-01"
		d.validate_update_after_submit()

	def test_varchar_length(self):
		d = self.test_insert()
		d.sender = "abcde" * 100 + "@user.com"
		self.assertRaises(jingrow.CharacterLengthExceededError, d.save)

	def test_xss_filter(self):
		d = self.test_insert()

		# script
		xss = '<script>alert("XSS")</script>'
		escaped_xss = xss.replace("<", "&lt;").replace(">", "&gt;")
		d.subject += xss
		d.save()
		d.reload()

		self.assertTrue(xss not in d.subject)
		self.assertTrue(escaped_xss in d.subject)

		# onload
		xss = '<div onload="alert("XSS")">Test</div>'
		escaped_xss = "<div>Test</div>"
		d.subject += xss
		d.save()
		d.reload()

		self.assertTrue(xss not in d.subject)
		self.assertTrue(escaped_xss in d.subject)

		# css attributes
		xss = '<div style="something: doesn\'t work; color: red;">Test</div>'
		escaped_xss = '<div style="">Test</div>'
		d.subject += xss
		d.save()
		d.reload()

		self.assertTrue(xss not in d.subject)
		self.assertTrue(escaped_xss in d.subject)

	def test_naming_series(self):
		data = ["TEST-", "TEST/17-18/.test_data./.####", "TEST.YYYY.MM.####"]

		for series in data:
			name = make_autoname(series)
			prefix = series

			if ".#" in series:
				prefix = series.rsplit(".", 1)[0]

			prefix = parse_naming_series(prefix)
			old_current = jingrow.db.get_value("Series", prefix, "current", order_by="name")

			revert_series_if_last(series, name)
			new_current = cint(jingrow.db.get_value("Series", prefix, "current", order_by="name"))

			self.assertEqual(cint(old_current) - 1, new_current)

	def test_non_negative_check(self):
		jingrow.delete_pg_if_exists("Currency", "Jingrow Coin", 1)

		d = jingrow.get_pg(
			{"pagetype": "Currency", "currency_name": "Jingrow Coin", "smallest_currency_fraction_value": -1}
		)

		self.assertRaises(jingrow.NonNegativeError, d.insert)

		d.set("smallest_currency_fraction_value", 1)
		d.insert()
		self.assertEqual(jingrow.db.get_value("Currency", d.name), d.name)

		jingrow.delete_pg_if_exists("Currency", "Jingrow Coin", 1)

	def test_get_formatted(self):
		jingrow.get_pg(
			{
				"pagetype": "PageType",
				"name": "Test Formatted",
				"module": "Custom",
				"custom": 1,
				"fields": [
					{"label": "Currency", "fieldname": "currency", "reqd": 1, "fieldtype": "Currency"},
				],
			}
		).insert(ignore_if_duplicate=True)

		jingrow.delete_pg_if_exists("Currency", "INR", 1)

		d = jingrow.get_pg(
			{
				"pagetype": "Currency",
				"currency_name": "INR",
				"symbol": "₹",
			}
		).insert()

		d = jingrow.get_pg({"pagetype": "Test Formatted", "currency": 100000})
		self.assertEqual(d.get_formatted("currency", currency="INR", format="#,###.##"), "₹ 100,000.00")

		# should work even if options aren't set in df
		# and currency param is not passed
		self.assertIn("0", d.get_formatted("currency"))

	def test_limit_for_get(self):
		pg = jingrow.get_pg("PageType", "PageType")
		# assuming PageType has more than 3 Data fields
		self.assertEqual(len(pg.get("fields", limit=3)), 3)

		# limit with filters
		self.assertEqual(len(pg.get("fields", filters={"fieldtype": "Data"}, limit=3)), 3)

	def test_virtual_fields(self):
		"""Virtual fields are accessible via API and Form views, whenever .as_dict is invoked"""
		jingrow.db.delete("Custom Field", {"dt": "Note", "fieldname": "age"})
		note = jingrow.new_pg("Note")
		note.content = "some content"
		note.title = jingrow.generate_hash(length=20)
		note.insert()

		def patch_note(class_=None):
			return patch("jingrow.controllers", new={jingrow.local.site: {"Note": class_ or CustomTestNote}})

		@contextmanager
		def customize_note(with_options=False):
			options = (
				"jingrow.utils.now_datetime() - jingrow.utils.get_datetime(pg.creation)"
				if with_options
				else ""
			)
			custom_field = jingrow.get_pg(
				{
					"pagetype": "Custom Field",
					"dt": "Note",
					"fieldname": "age",
					"fieldtype": "Data",
					"read_only": True,
					"is_virtual": True,
					"options": options,
				}
			)

			try:
				yield custom_field.insert(ignore_if_duplicate=True)
			finally:
				custom_field.delete()
				# to truly delete the field
				# creation is commited due to DDL
				jingrow.db.commit()

		with patch_note():
			pg = jingrow.get_last_pg("Note")
			self.assertIsInstance(pg, CustomTestNote)
			self.assertIsInstance(pg.age, timedelta)
			self.assertIsNone(pg.as_dict().get("age"))
			self.assertIsNone(pg.get_valid_dict().get("age"))

		with customize_note(), patch_note():
			pg = jingrow.get_last_pg("Note")
			self.assertIsInstance(pg, CustomTestNote)
			self.assertIsInstance(pg.age, timedelta)
			self.assertIsInstance(pg.as_dict().get("age"), timedelta)
			self.assertIsInstance(pg.get_valid_dict().get("age"), timedelta)

		# has virtual field, but age method is not a property
		with customize_note(), patch_note(class_=CustomNoteWithoutProperty):
			pg = jingrow.get_last_pg("Note")
			self.assertIsInstance(pg, CustomNoteWithoutProperty)
			self.assertNotIsInstance(type(pg).age, property)
			self.assertIsNone(pg.as_dict().get("age"))
			self.assertIsNone(pg.get_valid_dict().get("age"))

		with customize_note(with_options=True):
			pg = jingrow.get_last_pg("Note")
			self.assertIsInstance(pg, Note)
			self.assertIsInstance(pg.as_dict().get("age"), timedelta)
			self.assertIsInstance(pg.get_valid_dict().get("age"), timedelta)

	def test_run_method(self):
		pg = jingrow.get_last_pg("User")

		# Case 1: Override with a string
		pg.as_dict = ""

		# run_method should throw TypeError
		self.assertRaisesRegex(TypeError, "not callable", pg.run_method, "as_dict")

		# Case 2: Override with a function
		def my_as_dict(*args, **kwargs):
			return "success"

		pg.as_dict = my_as_dict

		# run_method should get overridden
		self.assertEqual(pg.run_method("as_dict"), "success")

	def test_extend(self):
		pg = jingrow.get_last_pg("User")
		self.assertRaises(ValueError, pg.extend, "user_emails", None)

		# allow calling pg.extend with iterable objects
		pg.extend("user_emails", ())
		pg.extend("user_emails", [])
		pg.extend("user_emails", (x for x in ()))

	def test_set(self):
		pg = jingrow.get_last_pg("User")

		# setting None should init a table field to empty list
		pg.set("user_emails", None)
		self.assertEqual(pg.user_emails, [])

		# setting a string value should fail
		self.assertRaises(TypeError, pg.set, "user_emails", "fail")
		# but not when loading from db
		pg.flags.ignore_children = True
		pg.update({"user_emails": "ok"})

	def test_pg_events(self):
		"""validate that all present pg events are correct methods"""

		for pagetype, pg_hooks in jingrow.get_pg_hooks().items():
			for _, hooks in pg_hooks.items():
				for hook in hooks:
					try:
						jingrow.get_attr(hook)
					except Exception as e:
						self.fail(f"Invalid pg hook: {pagetype}:{hook}\n{e}")

	def test_realtime_notify(self):
		todo = jingrow.new_pg("ToDo")
		todo.description = "this will trigger realtime update"
		todo.notify_update = Mock()
		todo.insert()
		self.assertEqual(todo.notify_update.call_count, 1)

		todo.reload()
		todo.flags.notify_update = False
		todo.description = "this won't trigger realtime update"
		todo.save()
		self.assertEqual(todo.notify_update.call_count, 1)

	def test_error_on_saving_new_pg_with_name(self):
		"""Trying to save a new pg with name should raise DoesNotExistError"""

		pg = jingrow.get_pg(
			{
				"pagetype": "ToDo",
				"description": "this should raise jingrow.DoesNotExistError",
				"name": "lets-trick-pg-save",
			}
		)

		self.assertRaises(jingrow.DoesNotExistError, pg.save)

	def test_validate_from_to_dates(self):
		pg = jingrow.new_pg("Web Page")
		pg.start_date = None
		pg.end_date = None
		pg.validate_from_to_dates("start_date", "end_date")

		pg.start_date = "2020-01-01"
		pg.end_date = None
		pg.validate_from_to_dates("start_date", "end_date")

		pg.start_date = None
		pg.end_date = "2020-12-31"
		pg.validate_from_to_dates("start_date", "end_date")

		pg.start_date = "2020-01-01"
		pg.end_date = "2020-12-31"
		pg.validate_from_to_dates("start_date", "end_date")

		pg.end_date = "2020-01-01"
		pg.start_date = "2020-12-31"
		self.assertRaises(
			jingrow.exceptions.InvalidDates, pg.validate_from_to_dates, "start_date", "end_date"
		)

	def test_db_set_singles(self):
		c = jingrow.get_pg("Contact Us Settings")
		key, val = "email_id", "admin1@example.com"
		c.db_set(key, val)
		changed_val = jingrow.db.get_single_value(c.pagetype, key)
		self.assertEqual(val, changed_val)


class TestDocumentWebView(JingrowTestCase):
	def get(self, path, user="Guest"):
		jingrow.set_user(user)
		set_request(method="GET", path=path)
		make_form_dict(jingrow.local.request)
		response = get_response()
		jingrow.set_user("Administrator")
		return response

	def test_web_view_link_authentication(self):
		todo = jingrow.get_pg({"pagetype": "ToDo", "description": "Test"}).insert()
		document_key = todo.get_document_share_key()

		# with old-style signature key
		update_system_settings({"allow_older_web_view_links": True}, True)
		old_document_key = todo.get_signature()
		url = f"/ToDo/{todo.name}?key={old_document_key}"
		self.assertEqual(self.get(url).status, "200 OK")

		update_system_settings({"allow_older_web_view_links": False}, True)
		self.assertEqual(self.get(url).status, "403 FORBIDDEN")

		# with valid key
		url = f"/ToDo/{todo.name}?key={document_key}"
		self.assertEqual(self.get(url).status, "200 OK")

		# with invalid key
		invalid_key_url = f"/ToDo/{todo.name}?key=INVALID_KEY"
		self.assertEqual(self.get(invalid_key_url).status, "403 FORBIDDEN")

		# expire the key
		document_key_pg = jingrow.get_pg("Page Share Key", {"key": document_key})
		document_key_pg.expires_on = "2020-01-01"
		document_key_pg.save(ignore_permissions=True)

		# with expired key
		self.assertEqual(self.get(url).status, "410 GONE")

		# without key
		url_without_key = f"/ToDo/{todo.name}"
		self.assertEqual(self.get(url_without_key).status, "403 FORBIDDEN")

		# Logged-in user can access the page without key
		self.assertEqual(self.get(url_without_key, "Administrator").status, "200 OK")

	def test_bulk_inserts(self):
		from jingrow.model.page import bulk_insert

		pagetype = "Role Profile"
		child_field = "roles"
		child_pagetype = jingrow.get_meta(pagetype).get_field(child_field).options

		sent_pgs = set()
		sent_child_pgs = set()

		def pg_generator():
			for _ in range(21):
				pg = jingrow.new_pg(pagetype)
				pg.role_profile = jingrow.generate_hash()
				pg.append("roles", {"role": "System Manager"})

				pg.set_new_name()
				pg.set_parent_in_children()

				sent_pgs.add(pg.name)
				sent_child_pgs.add(pg.roles[0].name)

				yield pg

		bulk_insert(pagetype, pg_generator(), chunk_size=5)

		all_pgs = set(jingrow.get_all(pagetype, pluck="name"))
		all_child_pgs = set(
			jingrow.get_all(
				child_pagetype, filters={"parenttype": pagetype, "parentfield": child_field}, pluck="name"
			)
		)
		self.assertEqual(sent_pgs - all_pgs, set(), "All pgs should be inserted")
		self.assertEqual(sent_child_pgs - all_child_pgs, set(), "All child pgs should be inserted")
