import sys, os
import pygame
from pygame.locals import *

SIZE = (320,256) #the 'Preview' setting Blender.
#small rez used in testing to save rendering time and player memory..

pygame.init()
screen = pygame.display.set_mode(SIZE)

try:
    videodir = sys.argv[1]

except:
    videodir = "/tmp/multitest"

timetracks = [] #not a dict to have the tracks in order - ok?

for d in os.listdir(videodir):
    if os.path.isdir(videodir + os.sep + d):
        track = []
        for f in os.listdir(videodir + os.sep + d):
            if not os.path.isdir(f):
                img = pygame.image.load(videodir + os.sep + d + os.sep + f)
                img = img.convert() #may make blitting much faster
                track.append(img)
            else:
                print "ignored directory when reading image files", f
                
        timetracks.append(track)

    else:
        print "ignored non-directory when reading time tracks", d

playing = True
track = timetracks[len(timetracks)/2]
pos = 1

pygame.mouse.set_visible(False)

clock = pygame.time.Clock()

def quit():
    pygame.mouse.set_visible(True)
    pygame.quit()
    

while True:
    if pygame.event.peek(QUIT):
        quit()

    for event in pygame.event.get(KEYDOWN):
        if event.key == K_ESCAPE:
            quit()

        elif event.key == K_SPACE:
            playing = not playing #toggles the boolean

        elif event.key == K_UP:
            index = (timetracks.index(track) + 1) % len(timetracks)
            track = timetracks[index]

        elif event.key == K_DOWN:
            index = (timetracks.index(track) - 1) % len(timetracks)
            track = timetracks[index]

        elif event.key == K_RIGHT:
            pos += 1
            pos %= len(track)

        elif event.key == K_LEFT:
            pos -= 1
            pos %= len(track) #?

    mousemotions = pygame.event.get(MOUSEMOTION)
    pygame.event.clear()
    if mousemotions: #checks if the list is nonempty
        mousemotion = mousemotions[-1] #only use the latest information
        rel_x = mousemotion.pos[0] / float(SIZE[0])
        rel_y = mousemotion.pos[1] / float(SIZE[1])
        track = timetracks[int(len(timetracks) * rel_y)]
        pos = int(len(track) * rel_x)
        

    #dx, dy = pygame.mouse.get_rel()
    #if (dx, dy) != (0,0):
    #    print dx, dy

    if playing:
        pos += 1
        pos %= len(track)

    clock.tick(25)
    screen.blit(track[pos], (10,10))
    pygame.display.flip()



