import os

import buttons
import display
import machine
import mch22
from neopixel import NeoPixel
from nvs import nvs_getstr
from ubinascii import a2b_base64

from .nyan import nyan
#from .nyan import nyan_snd

pixel_cache = NeoPixel(machine.Pin(5, machine.Pin.OUT), 5)
pixel_power = machine.Pin(19, machine.Pin.OUT)

my_name = nvs_getstr("owner", "nickname")

# calculate the nicknames dimension so we can center it (and don't need any hardcoded sizes)
text_x = int((display.width() - display.getTextWidth(my_name, "PermanentMarker36")) / 2)
text_y = display.height() - 20 - display.getTextHeight(my_name, "PermanentMarker36")

currently_playing = False

def displayNext(i):
    display.drawFill(0xFFFFFF)
    display.drawPng(0, 0, nyan[i])
    display.drawText(text_x, text_y, my_name, 0xFFFFFF, "PermanentMarker36")
    display.flush()


def displayRainbow(j):
    for i in range(5):
        pixel_cache[i] = RAINBOW[(i + j) % len(RAINBOW)]
    pixel_cache.write()


def displayAnimated():
    i = 0
    j = 0
    while True:
        displayNext(i)
        i = (i + 1) % len(nyan)
        displayRainbow(j)
        j = (j + 1) % len(RAINBOW)
        machine.lightsleep(100)


def enablePixels(pressed):
    if pressed:
        if pixel_power.value():
            pixel_power.off()
        else:
            pixel_power.on()


def buttonExitApp(pressed):
    mch22.exit_python()


buttons.attach(buttons.BTN_HOME, buttonExitApp)
buttons.attach(buttons.BTN_B, buttonExitApp)
buttons.attach(buttons.BTN_A, enablePixels)


RAINBOW = [
    (146, 0, 211),
    (122, 0,  184),
    (100, 0, 157),
    (75, 0, 130),
    (50, 0, 172),
    (25, 0, 213),
    (0, 0, 255),
    (0, 85, 170),
    (0, 170, 85),
    (0, 255, 0),
    (85, 255, 0),
    (170, 255, 0),
    (255, 255, 0),
    (255, 213, 0),
    (255, 170, 0),
    (255, 86, 0),
    (255, 58, 0),
    (255,29, 0),
    (255, 0 ,0),
]
RAINBOW = [
    (9,0,13),
    (8,0,11),
    (6,0,9),
    (5,0,8),
    (3,0,8),
    (2,0,13),
    (0,0,16),
    (0,5,11),
    (0,11,5),
    (0,16,0),
    (5,16,0),
    (11,16,0),
    (16,16,0),
    (16,13,0),
    (16,57,0),
    (16,5,0),
    (16,3,0),
    (16,1,0),
    (16,0,0),
]

displayAnimated()
