# -*- coding: utf-8 -*-
#tenji.py
#jtalk/tenji.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2012 Masataka.Shinke, Takuya Nishimoto

import unicodedata
import re
from tenjidic import *

def isKana(c):
	return re.search(ur'[ァ-ヶ]', c)
# return c in u'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン'

def tenji(Val):
	RetValues = u""
	pos = 0
	gaiji = False
	num = False
	Values = unicodedata.normalize('NFKC',Val)

	NewValues = ''
	for c in Values:
		if c in dic_symbols:
			NewValues += dic_symbols[c]
		else:
			NewValues += c
	Values = NewValues

	while pos < len(Values):
		#Numeric
		if Values[pos] in dic2:
			gaiji = False
			num = True
			RetValues += dic2.get(Values[pos])[0]
			while Values[pos] in dic2:
				RetValues += dic2.get(Values[pos])[1]
				pos += 1
				if pos >= len(Values):
					break
		#Lower case alphabet
		elif Values[pos] in dic3:
			if not gaiji:
				RetValues += dic3.get(Values[pos])[0]
			gaiji = True
			while Values[pos] in dic3:
				RetValues += dic3.get(Values[pos])[1]
				pos += 1
				if pos >= len(Values):
					break
		#Upper case alphabet
		elif Values[pos] in dic4:
			if not gaiji:
				RetValues += dic4.get(Values[pos])[0]
			RetValues += dic4.get(Values[pos])[1]
			gaiji = True
			if (Values[pos] in dic4) and (pos+1 < len(Values)):
				if Values[pos+1] in dic4:
					RetValues += dic4.get(Values[pos])[1]
			while Values[pos] in dic4:
				RetValues += dic4.get(Values[pos])[2]
				pos += 1
				if pos >= len(Values):
					break
		#Two kana characters
		elif (Values[pos:pos+2] in dic1) and (pos+1 < len(Values)):
			if num:
				RetValues += u'⠤'
				num = False
			RetValues += dic1.get(Values[pos:pos+2])
			gaiji = False
			pos += 2
		#One kana character or symbols
		elif Values[pos] in dic1:
			if gaiji and isKana(Values[pos]):
				RetValues += u'⠤'
			elif num and Values[pos] != '.':
				RetValues += u'⠤'
				num = False
			RetValues += dic1.get(Values[pos])
			gaiji = False
			pos += 1
		#Braille should not be changed
		elif 0x2800 <= ord(Values[pos]) and ord(Values[pos]) <= 0x28ff:
			gaiji = False
			num = False
			RetValues += Values[pos]
			pos += 1
		#Exception
		else:
			gaiji = False
			num = False
			RetValues += u"□"
			pos += 1
	return RetValues
