import ice40, display, buttons, mascot, stm32

filename = "/proto2.bin"

try:
    directory = '/'.join(__file__.split('/')[:-1])
except:
    directory = ''

def draw(text, color):
    display.drawFill(0x000000)
    display.drawText(0, 0, text, color, "ocra16", 1, 2)
    (w,h,_,_) = display.pngInfo(mascot.snek)
    display.drawPng(display.width() - w, display.height() - h, mascot.snek)
    display.flush()


draw("Programming bitstream...\n"+directory+filename, 0xFFFF00)

try:
    with open(directory+filename, "rb") as f:
        bitstream = f.read()
        try:
            stm32.lcd_fpga(True)
            ice40.load(bitstream)
            if ice40.done():
                pass
                #draw("Success!\nBitstream loaded", 0x00FF00)
            else:
                draw("Failed!\nFPGA not done", 0xFF0000)
        except:
            draw("Failed!\nCommunication error", 0xFF0000)
except:
    draw("Failed!\nFile not found\n"+directory+filename, 0xFF0000)