# -*- coding: utf-8 -*-
import os
import re
from gmisclib import die
from gmisclib import g_encode
from gmisclib import nicknames


class NoPhonemeToFormat(ValueError):
	def __init__(self, *s):
		ValueError.__init__(self, *s)


_brkt = re.compile(r'\[|\]|%')
def dict_format(s):
	assert isinstance(s, str), "s=%s" % repr(s)
	# if not s:
		# raise NoPhonemeToFormat("lbl='%s'" % s)
	return _brkt.sub(lambda x: '%%%d' % ord(x.group(0)), s)


_e = g_encode.encoder(allowed='abcdefghijklmnopqrstuvwxyz0123456789', eschar='_')
_upper = re.compile('[A-Z_]')
def HTKformat(s):
	assert isinstance(s, str), "s=%s" % repr(s)
	if not s:
		raise NoPhonemeToFormat("lbl='%s'" % s)
	s = _e.fwd(s)
	s = _upper.sub(lambda x: '_%s' % x.group(0).lower(), s)
	return 'z' + s


_Upper = re.compile('_([a-z_])')
def HTKiformat(s):
	assert s.startswith('z')
	s = s[1:]
	s = _Upper.sub(lambda x: x.group(1).upper(), s)
	return _e.back(s)



def write_phones(fn, ph, ncol=1):
	"""Write phonemes out to a 1-column MLF file."""
	die.info('Write %d phones to %s' % (len(ph), fn))
	assert ph
	fd = open(fn, 'w')
	# fd.write('#!MLF!#\n')
	# fd.write('"*/%s"\n' % fn)
	for p in ph:
		p.writeMLF(fd, ncol=ncol)
	# fd.write('.\n')
	fd.close()

def write_phonemap(root, allphones):
	m = open(os.path.join(root, 'phonemap'), 'w')
	gtmp = []
	for p in sorted(allphones):
		pm = HTKformat(p)
		m.write('%s %s\n' % (p, pm))
		gtmp.append(pm)
	g = open(os.path.join(root, 'generated_phones'), 'w')
	g.write('\n'.join(gtmp) + '\n')


#obsolete
def write_phonelist(root, allphones):
	m = open(os.path.join(root, 'phonemap'), 'w')
	d = open(os.path.join(root, 'dict'), 'w')
	df = open(os.path.join(root, 'dict_final'), 'w')
	gtmp = []
	for p in sorted(allphones):
		pm = HTKformat(p)
		m.write('%s %s\n' % (p, pm))
		d.write('%s %s\n' % (pm, pm))
		df.write('%s [%s] %s\n' % (pm, dict_format(p), pm))
		gtmp.append(pm)
	g = open(os.path.join(root, 'generated_phones'), 'w')
	g.write(' '.join(gtmp) + '\n')

