import time, sys
import pytilities as utils

encode = {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..',
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
'0': '-----',
'?': '..--..',
'!': '-.-.--',
'.': '.-.-.-',
' ': '/'
}

decode = {
'.-': 'A',
'-...': 'B',
'-.-.': 'C',
'-..': 'D',
'.': 'E',
'..-.': 'F',
'--.': 'G',
'....': 'H',
'..': 'I',
'.---': 'J',
'-.-': 'K',
'.-..': 'L',
'--': 'M',
'-.': 'N',
'---': 'O',
'.--.': 'P',
'--.-': 'Q',
'.-.': 'R',
'...': 'S',
'-': 'T',
'..-': 'U',
'...-': 'V',
'.--': 'W',
'-..-': 'X',
'-.--': 'Z',
'.----': '1',
'..---': '2',
'...--': '3',
'....-': '4',
'.....': '5',
'-....': '6',
'--...': '7',
'---..': '8',
'----.': '9',
'-----': '0',
'.-.-.-': '.',
'..--..': '?',
'-.-.--': '!',
'/': ' '
}
try:
	utils.slowprint('This is a morse code translator, made by JSD-Games.')
	utils.slowprint('Currently, the 26 letters, the nine digits, the question mark (?),\nthe exclamation mark (!), the period (.), and the space ( ) are supported.')
	utils.slowprint('When encoding, use spaces between letters and forward slashes between words. For example:\n.... .. / - .... . .-. . -.-.--')
except KeyboardInterrupt:
	sys.exit()

def main():
	utils.slowprint('Would you like to\nE)ncode,\nD)ecode,\nor QUIT?')
	act = input('> ').upper()

	if act == 'E' or act == 'ENCODE':
		utils.slowprint('Please enter the string you would like to encode.')
		string = input('> ').upper()
		newstring = ''
		for char in string:
			try:
				newchar = encode[char]
			except KeyError:
				utils.slowprint('You entered a character that is not yet supported.\nPlease try again, and make sure all the characters you type are supported.')
				main()
			newstring = newstring + newchar + ' '
		utils.slowprint('Your morse code message is:')
		utils.slowprint(newstring)
		print()
		main()
	elif act == 'D' or act == 'DECODE':
		utils.slowprint('Please enter the string you would like to decode.')
		string = input('> ').upper()
		spring = string.split()
		newstring = ''
		for char in spring:
			try:
				newchar = decode[char]
			except KeyError:
				utils.slowprint('You entered a character that is not yet supported or is not valid morse.\nPlease try again, and make sure all the characters you type are supported.')
				main()
			newstring = newstring + newchar
		utils.slowprint('Your decoded code message is:')
		utils.slowprint(newstring)
		print()
		main()
	elif act == 'QUIT':
		sys.exit()
	else:
		utils.slowprint('Please enter a valid command.')
		main()
try:
	main()
except KeyboardInterrupt:
	sys.exit()
