from tidal import display
from app import App
import lodepng

class png:
	def __init__(self, w, h, buf):
		self.w = w
		self.h = h
		self.buf = buf
	
	@staticmethod
	def load(filename):
		return png(*lodepng.decode565(filename))
	
	def draw(self, x, y):
		display.blit_buffer(self.buf, x, y, self.w, self.h)


class patarty(App):
	BOUNCE = [48, 33, 21, 12, 5, 1, 0, 1, 5, 12, 21, 33]
	COLOURS = [0x033F, 0xF980, 0x0666, 0x0000]
	PNGS = [
		"apps/microPatarty/patarty_blue.png",
		"apps/microPatarty/patarty_orange.png",
		"apps/microPatarty/patarty_green.png",
		"apps/microPatarty/patarty_black.png"
	]
	
	def on_activate(self):
		super().on_activate()
		self.patarty_pngs = [png.load(p) for p in self.PNGS]
		self.tick = 0
		self.timer = self.periodic(20, self.draw_patarty)
	
	def draw_patarty(self):
		colour_i = (self.tick / 48) % 4
		colour = self.COLOURS[colour_i]
		png = self.patarty_pngs[colour_i]
		
		cycle_i = self.tick % 12
		y = self.BOUNCE[cycle_i]
		prev_y = self.BOUNCE[(cycle_i - 1) % 12]
		
		png.draw(0, self.BOUNCE[cycle_i])
		
		if cycle_i == 0:
			display.fill_rect(0, 0, 135, 48, colour)
		elif cycle_i < 7:
			display.fill_rect(0, 192 + y, 135, prev_y - y, colour)
		else:
			display.fill_rect(0, prev_y, 135, y - prev_y, colour)
		
		self.tick = self.tick + 1

main = patarty