# Copyright (c) 2013, JINGROW and contributors
# License: MIT. See LICENSE
import jingrow
from jingrow import _

field_map = {
	"Contact": [
		"first_name",
		"last_name",
		"address",
		"phone",
		"mobile_no",
		"email_id",
		"is_primary_contact",
	],
	"Address": [
		"address_line1",
		"address_line2",
		"city",
		"state",
		"pincode",
		"country",
		"is_primary_address",
	],
}


def execute(filters=None):
	columns, data = get_columns(filters), get_data(filters)
	return columns, data


def get_columns(filters):
	return [
		"{reference_pagetype}:Link/{reference_pagetype}".format(
			reference_pagetype=filters.get("reference_pagetype")
		),
		"Address Line 1",
		"Address Line 2",
		"City",
		"State",
		"Postal Code",
		"Country",
		"Is Primary Address:Check",
		"First Name",
		"Last Name",
		"Address",
		"Phone",
		"Email Id",
		"Is Primary Contact:Check",
	]


def get_data(filters):
	reference_pagetype = filters.get("reference_pagetype")
	reference_name = filters.get("reference_name")

	return get_reference_addresses_and_contact(reference_pagetype, reference_name)


def get_reference_addresses_and_contact(reference_pagetype, reference_name):
	data = []
	filters = None
	reference_details = jingrow._dict()

	if not reference_pagetype:
		return []

	if reference_name:
		filters = {"name": reference_name}

	reference_list = [
		d[0] for d in jingrow.get_list(reference_pagetype, filters=filters, fields=["name"], as_list=True)
	]

	for d in reference_list:
		reference_details.setdefault(d, jingrow._dict())
	reference_details = get_reference_details(reference_pagetype, "Address", reference_list, reference_details)
	reference_details = get_reference_details(reference_pagetype, "Contact", reference_list, reference_details)

	for reference_name, details in reference_details.items():
		addresses = details.get("address", [])
		contacts = details.get("contact", [])
		if not any([addresses, contacts]):
			result = [reference_name]
			result.extend(add_blank_columns_for("Address"))
			result.extend(add_blank_columns_for("Contact"))
			data.append(result)
		else:
			addresses = list(map(list, addresses))
			contacts = list(map(list, contacts))

			max_length = max(len(addresses), len(contacts))
			for idx in range(0, max_length):
				result = [reference_name]

				result.extend(addresses[idx] if idx < len(addresses) else add_blank_columns_for("Address"))
				result.extend(contacts[idx] if idx < len(contacts) else add_blank_columns_for("Contact"))

				data.append(result)

	return data


def get_reference_details(reference_pagetype, pagetype, reference_list, reference_details):
	filters = [
		["Dynamic Link", "link_pagetype", "=", reference_pagetype],
		["Dynamic Link", "link_name", "in", reference_list],
	]
	fields = ["`tabDynamic Link`.link_name", *field_map.get(pagetype, [])]

	records = jingrow.get_list(pagetype, filters=filters, fields=fields, as_list=True)
	temp_records = [d[1:] for d in records]

	if not reference_list:
		jingrow.throw(_("No records present in {0}").format(reference_pagetype))

	reference_details[reference_list[0]][jingrow.scrub(pagetype)] = temp_records
	return reference_details


def add_blank_columns_for(pagetype):
	return ["" for field in field_map.get(pagetype, [])]
