import tidal
from app import App
from scheduler import get_scheduler

class SigilMaker(App):
    def on_start(self):
        super().on_start()

    def on_activate(self):
        super().on_activate()

        self.cursor_x = int(tidal.display.width() / 2)
        self.cursor_y = int(tidal.display.height() / 2)
        self.a_pressed = True
        self.b_pressed = True
        self.points = []
        self.update_task = None

        tidal.display.fill(tidal.BLACK)

        # We want to be able to see the sigil while meditating on it so don't turn off the screen!
        get_scheduler().set_sleep_enabled(False)
        
        self.update()

    def on_deactivate(self):
        super().on_deactivate()
        self.update_task.cancel()
        
        # Okay, now you can turn the screen off
        get_scheduler().set_sleep_enabled(False)

    def add_point(self):
        self.points.append((int(self.cursor_x), int(self.cursor_y)))
        
    def remove_point(self):
        if len(self.points) > 0:
            self.points.pop()

    def update(self):
        tidal.display.hline(int(self.cursor_x-2), int(self.cursor_y), 5, tidal.BLACK)
        tidal.display.vline(int(self.cursor_x), int(self.cursor_y-2), 5, tidal.BLACK)
    
        if tidal.JOY_LEFT.value() == 0 and self.cursor_x > 0:
            self.cursor_x -= 1
        if tidal.JOY_RIGHT.value() == 0 and self.cursor_x < tidal.display.width():
            self.cursor_x += 1
        if tidal.JOY_UP.value() == 0 and self.cursor_y > 0:
            self.cursor_y -= 1
        if tidal.JOY_DOWN.value() == 0 and self.cursor_y < tidal.display.height():
            self.cursor_y += 1

        
        if tidal.BUTTON_A.value() == 0 or tidal.JOY_CENTRE.value() == 0:
            if not self.a_pressed:
                self.add_point()
            
            self.a_pressed = True
        else:
            self.a_pressed = False
            
        if tidal.BUTTON_B.value():
            if not self.b_pressed:
                self.remove_point()
                tidal.display.fill(tidal.BLACK)
            self.b_pressed = True
        else:
            self.b_pressed = False
        
        
        self.draw()
        
        tidal.display.hline(int(self.cursor_x-2), int(self.cursor_y), 5, tidal.RED)
        tidal.display.vline(int(self.cursor_x), int(self.cursor_y-2), 5, tidal.RED)
        
        self.update_task = self.after(33, self.update)

    def draw(self):
        if (len(self.points) < 2):
            return
        
        for i in range(1, len(self.points)):
            tidal.display.line(self.points[i-1][0], self.points[i-1][1], self.points[i][0], self.points[i][1], tidal.WHITE)

main=SigilMaker