from tidal import *
from app import App

# Waving pride flag (move each color up and down)

class AnimatedPride(App):
    
    BG = WHITE
    FG = BLACK
    DISPLAY_WIDTH = display.width()
    DISPLAY_HEIGHT = display.height()

    COLORS = [RED, color565(255, 153, 0), YELLOW, GREEN, BLUE, color565(204, 0, 255)]
    LINE_HEIGHT = (DISPLAY_WIDTH // len(COLORS))

    LEN = len(COLORS)*4

    def __init__(self):
        super().__init__()
        self.offset = -1
        self.timer = None
        self.colors = []

        _offset = self.__offset = (0 - (self.LEN / 2))

        for i in range(len(self.COLORS)):
            color = {
                'color': self.COLORS[i],
                'offset': int(_offset),
                'inverse': True
            }
            _offset += self.LEN / len(self.COLORS)
            self.colors.append(color)

    def on_activate(self):
        super().on_activate()
        self.update_rainbow()
        self.timer = self.periodic(30, self.update_rainbow)
    
    def on_deactivate(self):
        super().on_deactivate()
        self.timer.cancel()

    def update_rainbow(self):
        i = 0
        block_len = self.DISPLAY_HEIGHT - int(self.LEN)

        for color in self.colors:
            left_offset = int(abs(self.__offset)) + color['offset']
            display.fill_rect(i * self.LINE_HEIGHT, left_offset, self.LINE_HEIGHT, block_len, color['color'])
            # fill left and right of color with black
            display.fill_rect(i * self.LINE_HEIGHT, 0, self.LINE_HEIGHT, left_offset, BLACK)
            display.fill_rect(i * self.LINE_HEIGHT, left_offset + block_len, self.LINE_HEIGHT, self.LEN - left_offset, BLACK)

            if (color['color'] == RED):
                print(f"{i=} {left_offset=} {block_len=} {self.DISPLAY_HEIGHT=}")
            
            if (left_offset < 1) or (left_offset + block_len >= self.DISPLAY_HEIGHT-1):
                color['inverse'] = not color['inverse']

            if color['inverse']:
                color['offset'] -= 1
            else:
                color['offset'] += 1
            i += 1

# Set the entrypoint for the app launher
main = AnimatedPride