import jingrow
import jingrow.defaults
from jingrow.contacts.report.addresses_and_contacts.addresses_and_contacts import get_data
from jingrow.tests.utils import JingrowTestCase


def get_custom_linked_pagetype():
	if bool(jingrow.get_all("PageType", filters={"name": "Test Custom Pagetype"})):
		return

	pg = jingrow.get_pg(
		{
			"pagetype": "PageType",
			"module": "Core",
			"custom": 1,
			"fields": [
				{"label": "Test Field", "fieldname": "test_field", "fieldtype": "Data"},
				{"label": "Contact HTML", "fieldname": "contact_html", "fieldtype": "HTML"},
				{"label": "Address HTML", "fieldname": "address_html", "fieldtype": "HTML"},
			],
			"permissions": [{"role": "System Manager", "read": 1}],
			"name": "Test Custom Pagetype",
		}
	)
	pg.insert()


def get_custom_pg_for_address_and_contacts():
	get_custom_linked_pagetype()
	return jingrow.get_pg(
		{
			"pagetype": "Test Custom Pagetype",
			"test_field": "Hello",
		}
	).insert()


def create_linked_address(link_list):
	if jingrow.flags.test_address_created:
		return

	address = jingrow.get_pg(
		{
			"pagetype": "Address",
			"address_title": "_Test Address",
			"address_type": "Billing",
			"address_line1": "test address line 1",
			"address_line2": "test address line 2",
			"city": "Milan",
			"country": "Italy",
		}
	)

	for name in link_list:
		address.append("links", {"link_pagetype": "Test Custom Pagetype", "link_name": name})

	address.insert()
	jingrow.flags.test_address_created = True

	return address.name


def create_linked_contact(link_list, address):
	if jingrow.flags.test_contact_created:
		return

	contact = jingrow.get_pg(
		{
			"pagetype": "Contact",
			"salutation": "Mr",
			"first_name": "_Test First Name",
			"last_name": "_Test Last Name",
			"is_primary_contact": 1,
			"address": address,
			"status": "Open",
		}
	)
	contact.add_email("test_contact@example.com", is_primary=True)
	contact.add_phone("+91 0000000000", is_primary_phone=True)

	for name in link_list:
		contact.append("links", {"link_pagetype": "Test Custom Pagetype", "link_name": name})

	contact.insert(ignore_permissions=True)
	jingrow.flags.test_contact_created = True


class TestAddressesAndContacts(JingrowTestCase):
	def test_get_data(self):
		linked_pgs = [get_custom_pg_for_address_and_contacts()]
		links_list = [item.name for item in linked_pgs]
		d = create_linked_address(links_list)
		create_linked_contact(links_list, d)
		report_data = get_data({"reference_pagetype": "Test Custom Pagetype"})
		for idx, link in enumerate(links_list):
			test_item = [
				link,
				"test address line 1",
				"test address line 2",
				"Milan",
				None,
				None,
				"Italy",
				0,
				"_Test First Name",
				"_Test Last Name",
				"_Test Address-Billing",
				"+91 0000000000",
				"",
				"test_contact@example.com",
				1,
			]
			self.assertListEqual(test_item, report_data[idx])
