import pyglet
from .tilemanager import TileManager

class PygletWrapper:
    def __init__(self):
        self.window = pyglet.window.Window(800, 600, "My Game")
        self.window.push_handlers(self)
        self.running = True

    def on_draw(self):
        self.window.clear()
        # Render your game here

    def on_close(self):
        self.running = False

    def handle_events(self):
        pyglet.clock.tick()
        self.window.dispatch_events()
        return not self.running

    def clear_screen(self, color=(0, 0, 0, 255)):
        pyglet.gl.glClearColor(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0, color[3] / 255.0)
        self.window.clear()

    def present_renderer(self):
        self.window.flip()

    def quit(self):
        pyglet.app.exit()
        
    def load_spritesheet(self, name, path):
        image = pyglet.image.load(path)
        self.spritesheets[name] = image
        self.tile_managers[name] = TileManager(path.replace('.png', '.xml'))

    def render_sprite(self, name, x, y):
        sprite = pyglet.sprite.Sprite(self.spritesheets[name], x, y)
        sprite.draw()

    def render_tile(self, spritesheet_name, tile_name, x, y):
        tile_rect = self.tile_managers[spritesheet_name].get_tile_rect(tile_name)
        if tile_rect is not None:
            image = self.spritesheets[spritesheet_name].get_region(*tile_rect)
            sprite = pyglet.sprite.Sprite(image, x, y)
            sprite.draw()