#I hate potatoes
#by HeNeArXn
#for On Track 2023
#at CCCamp 2023

from st3m.reactor import Responder
import st3m.run
import math
import leds
text = "the village kitchen had  to process 120 kg of potatoes, so I don't have enough time for a proper demo :/ -- HeNeArXn -- freetz to everyone from Lovebyte and the FieldFX byte jams!                         "



def hsv_to_rgb(h, s, v):
    if s == 0.0:
        return v, v, v
    i = int(h*6.0)
    f = (h*6.0) - i
    p = v*(1.0 - s)
    q = v*(1.0 - s*f)
    t = v*(1.0 - s*(1.0-f))
    i = i%6
    if i == 0:
        return v, t, p
    if i == 1:
        return q, v, p
    if i == 2:
        return p, v, t
    if i == 3:
        return p, q, v
    if i == 4:
        return t, p, v
    if i == 5:
        return v, p, q
    # Cannot get here

class Example(Responder):
    def __init__(self) -> None:
        self._x = 0
        self.t = 0.0
        self.offsets= False
        self.flashoffset=len("the village kitchen had to process 120 kg of potatoes, so I don't have enough time for a proper demo :/ -- ")
        self.flashtriggered=False
        leds.set_brightness(255)

    def draw(self, ctx: Context) -> None:
        ctx.text_baseline = ctx.MIDDLE
        ctx.font_size = 80
        ctx.font = ctx.get_font_name(5)

        if not self.offsets:
            self.offsets=[0]
            last=0
            for i in range(len(text)):
                x=last+ctx.text_width(text[i])+10
                self.offsets.append(x)
                last=x


        # Paint the background black
        ctx.rgb(0, 0, 0).rectangle(-120, -120, 240, 240).fill()



        #ctx.rgb(0, 0, 0).rectangle(-120, -120, 240, 240).fill()
        ctx.line_width = 14

        for i in range(-240,240,20):
            r,g,b=hsv_to_rgb((i/(480.*0.5)+0.3+self.t/4000)%1.0,0.8,0.8)
            ctx.rgb(r,g,b).rectangle(-240,i, 480,20).fill()


        ctx.rgb(1,1,1)
        for i in range(len(text)):
            x=self._x+self.offsets[i]
            #ctx.rgb(self._x+30*i,self._x+30*i,self._x+30*i)
            ctx.move_to(x, 15*math.sin((x)/12)+20*math.cos((x)/22))
            ctx.save()
            ctx.text(text[i])
            ctx.restore()

        if not self.flashtriggered:
            if self._x + self.offsets[self.flashoffset] <0:
                self.flashtriggered=self.t
        if self.flashtriggered:
            if (self.t-self.flashtriggered)<6000:
                b=(self.t%500)*2/1000
                leds.set_all_rgb(b,b,b)
                leds.update()
            else:
                leds.set_all_rgb(0,0,0)
                leds.update()
                self.flashtriggered=-1000000


    def think(self, ins: InputState, delta_ms: int) -> None:
        #direction = ins.buttons.app # -1 (left), 1 (right), or 2 (pressed)

        self._x -= 85 * delta_ms / 1000
        self.t += delta_ms
        #self._x = self._x % 480
st3m.run.run_responder(Example())
