import ujson
import utime

import buttons
import color
import display
import leds
import pride


# Dimensions of the screen
X_LEN = 160
Y_LEN = 80


class flagGen():
    """Iterate forward and backwards over the flags.

    Args:
        flags (list): List of flags to iterate over.
        start_flag (str): Name of the flag to start with in the list.
    """

    def __init__(self, flags, start_flag='rainbow'):
        self.flags = flags
        self.start_flag = start_flag
        self.current_flag = flags.index(start_flag)

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        self.current_flag += 1

        if self.current_flag >= (len(self.flags) - 1):
            self.current_flag = 0

        return self.flags[self.current_flag]

    def previous(self):
        self.current_flag -= 1

        if self.current_flag < 0:
            self.current_flag = len(self.flags) - 1

        return self.flags[self.current_flag]


def read_nickname():
    try:
        with open('nickname.json') as file:
            nickname = ujson.load(file)
    except FileNotFoundError:
        with open('nickname.txt') as file:
            nick_file = str(file.read())
            nickname = {'nickname': nick_file}

    return nickname


def flashlight(status=True):
    """Turns all the leds to solid bright white."""

    if status:
        leds.set_powersave(True)
        leds.set_all([color.WHITE] * 18)
        leds.dim_bottom(8)
        leds.dim_top(8)
    else:
        leds.dim_bottom(0)
        leds.dim_top(0)

    leds.update()


def main():
    nick_details = read_nickname()
    nickname = nick_details['nickname']
    subtitle = nick_details.get('subtitle')
    pronouns = nick_details.get('pronouns')

    title_x = Y_LEN - round(len(nickname) / 2 * 14)
    title_y = 18 if subtitle else 30

    if subtitle:
        subtitle_x = Y_LEN - round(len(subtitle) / 2 * 14)
        subtitle_y = 42

    start_flag = 'rainbow'
    flags = list(pride.flags)
    flag_gen = flagGen(flags, start_flag=start_flag)

    # Set the default flag to draw on first run
    new_flag = start_flag
    counter = 0
    change = True
    alternate = True
    flash_status = False
    while True:
        if counter % 4 == 0:
            change = True
            counter = 0
            alternate = not alternate
        counter += 1

        utime.sleep_ms(500)
        # Check if button is pressed
        button_left = buttons.read(buttons.BOTTOM_LEFT)
        button_right = buttons.read(buttons.BOTTOM_RIGHT)

        # Check what it was
        if button_left and button_right:
            flash_status = not flash_status
            flashlight(flash_status)
            continue
        if button_left:
            new_flag = flag_gen.previous()
            change = True
        elif button_right:
            new_flag = flag_gen.next()
            change = True
        elif not change or not pronouns:
            continue

        # Switch flag
        pride.show_display(flag=new_flag)

        # Re-draw screen
        with display.open() as disp:
            # Print text if there's no pronouns, or it's every fourth run
            if not pronouns or alternate:
                disp.print(nickname, posx=title_x, posy=title_y)
                if subtitle:
                    disp.print(subtitle, posx=subtitle_x, posy=subtitle_y)
            else:
                text_height = 20
                total_height = text_height * len(pronouns)
                start_height = (Y_LEN / 2) - (total_height / 2)

                for num, pronoun in enumerate(pronouns):
                    # Current height is the top of the total height plus how many
                    # rows we are donwards
                    current_height = start_height + (text_height * num)
                    pronouns_x = Y_LEN - round(len(pronoun) / 2 * 14)

                    disp.print(pronoun, posx=pronouns_x, posy=int(current_height))

            disp.update()
        change = False


if __name__ == '__main__':
    main()