# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#


import cocos
from cocos.director import director
from cocos.sprite import Sprite
from cocos.actions import Delay, CallFunc
import pyglet
from pyglet.gl import *
import ctypes as ce
## the following is in case we want to get the images
## from other directories:
# pyglet.resource.path.append("/data/other/directory")
# pyglet.resource.reindex()


class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        self.sprite = Sprite('grossini.png')
        self.sprite.position = x/2, y/2
        self.add( self.sprite  )

    def on_enter(self):
        super(TestLayer, self).on_enter()
        print 'on_enter'
        action = Delay(2.0)+CallFunc(self.get_fbo)
        self.do(action)
        
    def get_fbo(self):
        print 'grabbing fbo'
        id = GLuint(0)
        glGenFramebuffersEXT (1, byref(id)) #pyglet.image.__init__ near 1537        
        #glGenFramebuffersEXT (1, id) # seems to work, and coherent with the delete call (?)         
        self._id = id.value
        self.do(Delay(2)+CallFunc(self.del_fbo))
        print 'id:', id
        print 'id.value', self._id
        print 'pt:', ce.byref(id)

    def del_fbo(self):
        print 'freeing fbo'
        #the code present in gl_framebuffer.py, no problem in win 32bits 
        id = GLuint(self._id)
        #glDeleteFramebuffersEXT(1, id) # like glDelTexture in pyglet\gl\__init__, near 395  
        glDeleteFramebuffersEXT(1, byref(id)) #pyglet.image.__init__ near 1537        

#pruebas:
# arriba con byref, abajo sin:  -> no veo errores
# arrib sin, abajo sin: -> no veo erores
# arriba sin, abajo con: -> no veo errores
# arriba con, abajo con: -> no veo errores


if __name__ == "__main__":
    director.init()
    test_layer = TestLayer ()
    main_scene = cocos.scene.Scene (test_layer)
    director.run (main_scene)
