"""
Displays your nickname defined in nickname.txt
on display and uses the top left LED to output
it in morse code

Based on
  - nickname.py by Card10-Team
  - micropython-morsecode by mampersat
"""




import utime,leds,os,display

FILENAME = 'nickname.txt'

CODE = {'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':'--..',
    '0':'-----','1':'.----','2':'..---','3':'...--','4':'....-',
    '5':'.....','6':'-....','7':'--...','8':'---..','9':'----.',
    '.':'.-.-.-',
    ',':'--..--',
    '?':'..--..',
    '/':'--..-.',
    '@':'.--.-.'
}

def render_nickname(title):
    with display.open() as disp:
        print("  D:clear")
        disp.clear()
        print("  D:print")
        disp.print(title, fg=[255,255,255], bg=[0,0,0], posx=80 - round(len(title) / 2 * 14), posy=18)
        print("  D:update")
        disp.update()
        print("  D:close")
        disp.close()
        return


def flash(t):
    leds.set(leds.TOP_LEFT, [255,0,0])
    utime.sleep(t)
    leds.set(leds.TOP_LEFT, [0,0,0])
    utime.sleep(t)
    return

def send(msg="CCCAMP19",tdot = 0.1):
    tdash = tdot * 3
    tspace = tdot * 2
    tword = tdot * 6
    for l in msg:
        print("Char: " + l)
        if l.upper() in CODE:
            c = CODE.get(l.upper())
            for e in c:
               if e==".":flash(tdot)
               if e=="-":flash(tdash)
               if e==" ":flash(tspace)
            utime.sleep(tword)
        else:
            print("   Unknown character, skipping")
    return


leds.clear()
#if FILENAME not in os.listdir("."):
#    print("nickname.txt missing")
#    render_error('nickname.txt', 'not found')
f = open(FILENAME, 'r')
nick = f.read()
f.close()
if len(nick) > 11:
    print('name too long')
elif len(nick) < 1:
    print('nick file empty')
else:
    print("Nickname is " + nick)
    print("LCD...")
    render_nickname(nick)
    print("Morseloop")
    while True:
        print("StartMorse")
        send(nick, 0.1)
        utime.sleep(0.5)