import pygame,os
import urllib
import StringIO
from pygame.locals import *
import thread,datetime

def maxSize(image, maxSize):
    imAspect = float(image.get_size()[0])/float(image.get_size()[1])
    outAspect = float(maxSize[0])/float(maxSize[1])

    if imAspect >= outAspect:
        #set to maxWidth x maxWidth/imAspect
        res = (maxSize[0], int((float(maxSize[0])/imAspect) + 0.5))
    else:
        #set to maxHeight*imAspect x maxHeight
        res = (int((float(maxSize[1])*imAspect) + 0.5), maxSize[1])
    return pygame.transform.scale(image,res)

def main():
  res = (1280,1024)
  pygame.init()
  
  files = urllib.urlopen("http://picsrv/?method=list").read().split("\n")
  files.pop()

  screen = pygame.display.set_mode(res, FULLSCREEN)
  pygame.mouse.set_visible(False)
  mysurf = pygame.surface.Surface((10,10))
  start = -100.0
  
  while 1:
   for file in files:
    hour = datetime.datetime.today().hour
    if hour > 21 or hour < 6:
      os.system("DISPLAY=:0.0 xset dpms force off")
      pygame.time.wait(60*1000)
    else:
      os.system("DISPLAY=:0.0 xset dpms force on")
      now = pygame.time.get_ticks()
      file = urllib.urlopen("http://picsrv/?method=resize&name="+file)
      string = file.read()
      fakefile = StringIO.StringIO(string)
      surface = pygame.image.load(fakefile, "x.jpg")
      surface = maxSize(surface,res)
      screen.fill((0,0,0))
      size = surface.get_size()
      pos = (res[0]/2-size[0]/2,res[1]/2-size[1]/2)
      screen.blit(surface, pos)
      pygame.display.update()
      for event in pygame.event.get():
        if event.type == QUIT:
          return
      pygame.time.wait(5*1000-(pygame.time.get_ticks()-now))

main()
