from tidal import *
from app import App
import os

DEFAULT_DISPLAY_TIME = 3000
DISPLAY_TIME_ADJUST = 1000
MINIMUM_DISPLAY_TIME = 1000
IMAGE_DIR = 'apps/slideshow/images'

class slideshowApp(App):
    def on_activate(self):
        super().on_activate()

        self.buttons.on_press(JOY_UP, lambda: self.auto_update_speed_adjust(DISPLAY_TIME_ADJUST))
        self.buttons.on_press(JOY_DOWN, lambda: self.auto_update_speed_adjust(-1*DISPLAY_TIME_ADJUST))
        self.buttons.on_press(JOY_LEFT, lambda: self.jump_to_image(-1))
        self.buttons.on_press(JOY_RIGHT, lambda: self.jump_to_image(1))
        self.buttons.on_press(JOY_CENTRE, lambda: self.toggle_auto_update())

        self.current_index = 0
        self.images = [(IMAGE_DIR + '/' + x) for x in os.listdir(IMAGE_DIR) if ((x.endswith('.jpg')) or (x.endswith('.jpeg')))]

        self.auto_update = True
        self.display_time = DEFAULT_DISPLAY_TIME
        self.timer_task = self.periodic(self.display_time, self.update)

        self.show_current_image()
        self.update_index(1)

    def update_index(self, increment):
        self.current_index += increment
        self.current_index = self.current_index % len(self.images)

    def show_current_image(self):
        display.jpg(self.images[self.current_index],0,0)

    def update(self):
        self.show_current_image()
        self.update_index(1)

    def jump_to_image(self, direction):
        if self.auto_update:
            self.timer_task.cancel()
            self.timer_task = self.periodic(self.display_time, self.update)
        self.update_index(direction)
        self.show_current_image()

    def toggle_auto_update(self):
        self.auto_update = False if self.auto_update else True
        if self.auto_update:
            self.timer_task.cancel()
            self.timer_task = self.periodic(self.display_time, self.update)
        else:
            self.timer_task.cancel()

    def auto_update_speed_adjust(self, adjust):
        self.display_time += adjust
        if self.display_time < MINIMUM_DISPLAY_TIME:
            self.display_time = MINIMUM_DISPLAY_TIME
        if self.auto_update:
            self.timer_task.cancel()
            self.timer_task = self.periodic(self.display_time, self.update)

    def on_deactivate(self):
        super().on_deactivate()
        self.timer_task.cancel()

main = slideshowApp