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

from markdownify import markdownify as md

import jingrow


def get_parent_pg(pg):
	"""Return document of `reference_pagetype`, `reference_pagetype`."""
	if not getattr(pg, "parent_pg", None):
		if pg.reference_pagetype and pg.reference_name:
			pg.parent_pg = jingrow.get_pg(pg.reference_pagetype, pg.reference_name)
		else:
			pg.parent_pg = None
	return pg.parent_pg


def set_timeline_pg(pg):
	"""Set timeline_pagetype and timeline_name"""
	parent_pg = get_parent_pg(pg)
	if (pg.timeline_pagetype and pg.timeline_name) or not parent_pg:
		return

	timeline_field = parent_pg.meta.timeline_field
	if not timeline_field:
		return

	pagetype = parent_pg.meta.get_link_pagetype(timeline_field)
	name = parent_pg.get(timeline_field)

	if pagetype and name:
		pg.timeline_pagetype = pagetype
		pg.timeline_name = name

	else:
		return


def find(list_of_dict, match_function):
	"""Returns a dict in a list of dicts on matching the conditions
	        provided in match function

	Usage:
	        list_of_dict = [{'name': 'Suraj'}, {'name': 'Aditya'}]

	        required_dict = find(list_of_dict, lambda d: d['name'] == 'Aditya')
	"""

	for entry in list_of_dict:
		if match_function(entry):
			return entry
	return None


def find_all(list_of_dict, match_function):
	"""Returns all matching dicts in a list of dicts.
	        Uses matching function to filter out the dicts

	Usage:
	        colored_shapes = [
	                {'color': 'red', 'shape': 'square'},
	                {'color': 'red', 'shape': 'circle'},
	                {'color': 'blue', 'shape': 'triangle'}
	        ]

	        red_shapes = find_all(colored_shapes, lambda d: d['color'] == 'red')
	"""
	return [entry for entry in list_of_dict if match_function(entry)]


def ljust_list(_list, length, fill_word=None):
	"""
	Similar to ljust but for list.

	Usage:
	        $ ljust_list([1, 2, 3], 5)
	        > [1, 2, 3, None, None]
	"""
	# make a copy to avoid mutation of passed list
	_list = list(_list)
	fill_length = length - len(_list)
	if fill_length > 0:
		_list.extend([fill_word] * fill_length)

	return _list


def html2text(html, strip_links=False, wrap=True):
	strip = ["a"] if strip_links else None
	return md(html, heading_style="ATX", strip=strip, wrap=wrap)
