import yaml
from parallels.core.utils.common import read_file


def pretty_yaml(cls, prefix=None):
	"""Set up YAML library to dump/load named tuple class as mapping."""
	if prefix is not None:
		prefix_str = "%s." % prefix
	else:
		prefix_str = ""

	tag = u'!%s%s' % (prefix_str, cls.__name__)

	def namedtuple_representer(dumper, data):
		return dumper.represent_mapping(tag, data._asdict())

	def namedtuple_constructor(loader, node):
		return cls(**loader.construct_mapping(node))

	yaml.add_representer(cls, namedtuple_representer)
	yaml.add_constructor(tag, namedtuple_constructor)

	return cls


def read_yaml(filename, file_may_be_absent=False, default=None):
	return read_file(filename, yaml.load, file_may_be_absent, default)


def write_yaml(filename, data):
	with open(filename, 'w') as dump_file:
		yaml.dump(data, dump_file, allow_unicode=True)