#!/usr/bin/env python

# View live images from a single or group of webcams

import gobject
import gtk
import pygtk
pygtk.require('2.0')
import glob

GMOTION_DIR = "/usr/local/var/gmotion"
GROUP_DIR = "default"
MOTION_SNAPSHOT_INTERVAL = 1  # seconds


class MainWindow:

    def destroy(self, widget):
        gtk.main_quit()

    def delete_event(self, widget, event):
        return False
    
    def __init__(self):

        def display_camera_images():
            for img, jpg in self.camera_image_data:
                img.set_from_file(jpg)
                img.show()
            return True

        win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        win.set_default_size(1100, 400)
        win.connect("delete_event", self.delete_event)
        win.connect("destroy", self.destroy)
        # TODO somehow tidy up any snapshots lying around
        #for fi in glob.glob(self.snapshot_dir + '/*.jpg'):
        #    os.remove(fi)
        #time.sleep(MOTION_SNAPSHOT_INTERVAL)
        self.camera_image_data = [(gtk.Image(), fi) for fi in glob.glob(GMOTION_DIR + "/Group/" + GROUP_DIR + "/Snapshot" + '/*.jpg')]
        # TODO add GUI for user to set number of columns of images in window
        swin = gtk.ScrolledWindow()
        swin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hbx = gtk.HBox()
        for img, jpg in self.camera_image_data:
            hbx.pack_start(img)
        swin.add_with_viewport(hbx)
        hbx.show()
        win.add(swin)
        swin.show()
        gobject.timeout_add(MOTION_SNAPSHOT_INTERVAL * 1000, display_camera_images)
        # TODO add sync. code
        win.show()

    def main(self):
        gtk.main()


print __name__
if __name__ == "__main__":
    base = MainWindow()
    base.main()
