# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
from jingrow.contacts.pagetype.address_template.address_template import get_default_address_template
from jingrow.tests.utils import JingrowTestCase
from jingrow.utils.jinja import validate_template


class TestAddressTemplate(JingrowTestCase):
	def setUp(self) -> None:
		jingrow.db.delete("Address Template", {"country": "India"})
		jingrow.db.delete("Address Template", {"country": "Brazil"})

	def test_default_address_template(self):
		validate_template(get_default_address_template())

	def test_default_is_unset(self):
		jingrow.get_pg({"pagetype": "Address Template", "country": "India", "is_default": 1}).insert()

		self.assertEqual(jingrow.db.get_value("Address Template", "India", "is_default"), 1)

		jingrow.get_pg({"pagetype": "Address Template", "country": "Brazil", "is_default": 1}).insert()

		self.assertEqual(jingrow.db.get_value("Address Template", "India", "is_default"), 0)
		self.assertEqual(jingrow.db.get_value("Address Template", "Brazil", "is_default"), 1)

	def test_delete_address_template(self):
		india = jingrow.get_pg({"pagetype": "Address Template", "country": "India", "is_default": 0}).insert()

		brazil = jingrow.get_pg(
			{"pagetype": "Address Template", "country": "Brazil", "is_default": 1}
		).insert()

		india.reload()  # might have been modified by the second template
		india.delete()  # should not raise an error

		self.assertRaises(jingrow.ValidationError, brazil.delete)
