# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
from jingrow.tests.utils import JingrowTestCase


class TestDynamicLinks(JingrowTestCase):
	def setUp(self):
		jingrow.db.delete("Email Unsubscribe")

	def test_delete_normal(self):
		event = jingrow.get_pg(
			{
				"pagetype": "Event",
				"subject": "test-for-delete",
				"starts_on": "2014-01-01",
				"event_type": "Public",
			}
		).insert()

		unsub = jingrow.get_pg(
			{
				"pagetype": "Email Unsubscribe",
				"email": "test@example.com",
				"reference_pagetype": event.pagetype,
				"reference_name": event.name,
			}
		).insert()

		event.delete()

		self.assertFalse(jingrow.db.exists("Email Unsubscribe", unsub.name))

	def test_delete_with_comment(self):
		event = jingrow.get_pg(
			{
				"pagetype": "Event",
				"subject": "test-for-delete-1",
				"starts_on": "2014-01-01",
				"event_type": "Public",
			}
		).insert()
		event.add_comment("Comment", "test")

		self.assertTrue(
			jingrow.get_all("Comment", filters={"reference_pagetype": "Event", "reference_name": event.name})
		)
		event.delete()
		self.assertFalse(
			jingrow.get_all("Comment", filters={"reference_pagetype": "Event", "reference_name": event.name})
		)

	def test_custom_fields(self):
		from jingrow.utils.testutils import add_custom_field, clear_custom_fields

		add_custom_field("Event", "test_ref_pg", "Link", "PageType")
		add_custom_field("Event", "test_ref_name", "Dynamic Link", "test_ref_pg")

		unsub = jingrow.get_pg(
			{"pagetype": "Email Unsubscribe", "email": "test@example.com", "global_unsubscribe": 1}
		).insert()

		event = jingrow.get_pg(
			{
				"pagetype": "Event",
				"subject": "test-for-delete-2",
				"starts_on": "2014-01-01",
				"event_type": "Public",
				"test_ref_pg": unsub.pagetype,
				"test_ref_name": unsub.name,
			}
		).insert()

		self.assertRaises(jingrow.LinkExistsError, unsub.delete)

		event.test_ref_pg = None
		event.test_ref_name = None
		event.save()

		unsub.delete()

		clear_custom_fields("Event")
		jingrow.db.commit()  # undo changes done by DDL
