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

import jingrow
from jingrow.contacts.pagetype.address.address import address_query, get_address_display
from jingrow.tests.utils import JingrowTestCase


class TestAddress(JingrowTestCase):
	def test_template_works(self):
		if not jingrow.db.exists("Address Template", "India"):
			jingrow.get_pg({"pagetype": "Address Template", "country": "India", "is_default": 1}).insert()

		if not jingrow.db.exists("Address", "_Test Address-Office"):
			jingrow.get_pg(
				{
					"address_line1": "_Test Address Line 1",
					"address_title": "_Test Address",
					"address_type": "Office",
					"city": "_Test City",
					"state": "Test State",
					"country": "India",
					"pagetype": "Address",
					"is_primary_address": 1,
					"phone": "+91 0000000000",
				}
			).insert()

		address = jingrow.get_list("Address")[0].name
		display = get_address_display(jingrow.get_pg("Address", address).as_dict())
		self.assertTrue(display)

	def test_address_query(self):
		def query(pagetype="Address", txt="", searchfield="name", start=0, page_len=20, filters=None):
			if filters is None:
				filters = {"link_pagetype": "User", "link_name": "Administrator"}
			return address_query(pagetype, txt, searchfield, start, page_len, filters)

		jingrow.get_pg(
			{
				"address_type": "Billing",
				"address_line1": "1",
				"city": "Mumbai",
				"state": "Maharashtra",
				"country": "India",
				"pagetype": "Address",
				"links": [
					{
						"link_pagetype": "User",
						"link_name": "Administrator",
					}
				],
			}
		).insert()

		self.assertGreaterEqual(len(query(txt="Admin")), 1)
		self.assertEqual(len(query(txt="what_zyx")), 0)
