import gst
from Togra import GstTexture

playbins = {}

def handle_error (bus, message, element):
    print "Got ERROR for %s" % (element.get_name())
    if element.set_state (gst.STATE_READY) == gst.STATE_CHANGE_ASYNC:
        element.get_state (gst.CLOCK_TIME_NONE)

def handle_eos (bus, message, element):
    print "Got EOS for %s" % (element.get_name())
    if element.set_state (gst.STATE_READY) == gst.STATE_CHANGE_ASYNC:
        if element.get_state (1 * gst.SECOND) == gst.STATE_CHANGE_ASYNC:
            print "Couldn't restart element"
            return

    print "Restarting..."
    element.set_state (gst.STATE_PLAYING)

def handle_new_pad (element, pad, more_pads, connect_to, location):
    s = pad.get_caps()
    mime_type = s[0].get_name()

    print location, "new pad of type", mime_type
    if mime_type.startswith("video/x-raw") and not connect_to.is_linked():
        pad.link (connect_to)

def get_texture_objects(locations, placeholder):
        global playbins
	textures = []
	for location in locations:
		texture = GstTexture(256, 256)
		sink = texture.getSink()

		pipeline = gst.element_factory_make ("playbin")
                pipeline.set_property ("video-sink", sink);

                if not location.startswith ("http://") and not location.startswith ("file://"):
                    location = "file://" + location

		pipeline.set_property("uri", location)
		pipeline.set_property("volume", 0.25)

                pipeline.get_bus().connect ('message::eos', handle_eos, pipeline)
                pipeline.get_bus().connect ('message::error', handle_error, pipeline)
                pipeline.get_bus().add_signal_watch()

		pipeline.set_state(gst.STATE_PAUSED)
		pipeline.set_state(gst.STATE_PLAYING)
		textures.append(texture)
                playbins[texture] = pipeline
	return textures

def change_res(texture, res):
        return

	sink = texture.getSink()
	sink.set_property("width", res)
	sink.set_property("height", res)

def change_vol(texture, gain):
        global playbins
        pb = playbins[texture];
        pb.set_property ("volume", gain)
        pass

