# Copyright (c) 2022, JINGROW and Contributors
# License: MIT. See LICENSE

from itertools import product

import jingrow
from jingrow.model.rename_page import get_link_fields


def update_linked_pagetypes(
	pagetype: str, pagename: str, linked_to: str, value: str, ignore_pagetypes: list | None = None
):
	"""
	linked_pagetype_info_list = list formed by get_fetch_fields() function
	pagename = Master PageType's name in which modification are made
	value = Value for the field thats set in other PageType's by fetching from Master PageType
	"""
	linked_pagetype_info_list = get_fetch_fields(pagetype, linked_to, ignore_pagetypes)

	for d in linked_pagetype_info_list:
		jingrow.db.set_value(
			d.pagetype,
			{
				d.master_fieldname: pagename,
				d.linked_to_fieldname: ("!=", value),
			},
			d.linked_to_fieldname,
			value,
		)


def get_fetch_fields(pagetype: str, linked_to: str, ignore_pagetypes: list | None = None) -> list[dict]:
	"""
	pagetype = Master PageType in which the changes are being made
	linked_to = PageType name of the field thats being updated in Master
	This function fetches list of all PageType where both pagetype and linked_to is found
	as link fields.
	Forms a list of dict in the form -
	        [{pagetype: , master_fieldname: , linked_to_fieldname: ]
	where
	        pagetype = PageType where changes need to be made
	        master_fieldname = Fieldname where options = pagetype
	        linked_to_fieldname = Fieldname where options = linked_to
	"""

	out = []
	master_list = get_link_fields(pagetype)
	linked_to_list = get_link_fields(linked_to)
	product_list = product(master_list, linked_to_list)

	for d in product_list:
		linked_pagetype_info = jingrow._dict()
		if (
			d[0]["parent"] == d[1]["parent"]
			and (not ignore_pagetypes or d[0]["parent"] not in ignore_pagetypes)
			and not d[1]["issingle"]
		):
			linked_pagetype_info.pagetype = d[0]["parent"]
			linked_pagetype_info.master_fieldname = d[0]["fieldname"]
			linked_pagetype_info.linked_to_fieldname = d[1]["fieldname"]
			out.append(linked_pagetype_info)

	return out
