import os


def list_target_panels():
	return list(_iter_target_panels())


def list_source_panels(target_panel):
	return list(_iter_source_panels(target_panel))


def load_target_panel_class(target_panel, module_name, class_name, optional=False):
	if optional:
		root_modules_dir = os.path.join(os.path.dirname(__file__), '..')
		if not os.path.exists(os.path.join(root_modules_dir, target_panel, '%s.py' % module_name)):
			# if module is optional and it does not exist - return None instead of raising import exception
			return None

	module = __import__(
		'parallels.%s.%s' % (target_panel, module_name),
		globals(), locals(), [class_name]
	)
	return getattr(module, class_name)


def load_source_panel_class(target_panel, source_panel, module_name, class_name, optional=False):
	if optional:
		root_modules_dir = os.path.join(os.path.dirname(__file__), '..')
		module_path = os.path.join(root_modules_dir, target_panel, 'source', source_panel, '%s.py' % module_name)
		if not os.path.exists(module_path):
			# if module is optional and it does not exist - return None instead of raising import exception
			return None
	module = __import__(
		'parallels.%s.source.%s.%s' % (target_panel, source_panel, module_name),
		globals(), locals(), [class_name]
	)
	return getattr(module, class_name)


def _iter_target_panels():
	root_modules_dir = os.path.join(os.path.dirname(__file__), '..')
	for module_dir in os.listdir(root_modules_dir):
		if os.path.isdir(os.path.join(root_modules_dir, module_dir)):
			if os.path.exists(os.path.join(root_modules_dir, module_dir, 'workflow.py')):
				yield module_dir


def _iter_source_panels(target_panel):
	root_modules_dir = os.path.join(os.path.dirname(__file__), '..')
	target_panel_dir = os.path.join(root_modules_dir, target_panel)
	source_panels_dir = os.path.join(target_panel_dir, 'source')

	if not os.path.exists(source_panels_dir):
		return

	for module_dir in os.listdir(source_panels_dir):
		if os.path.exists(os.path.join(source_panels_dir, module_dir, 'workflow.py')):
			yield module_dir
