import time
import my3dengine as m3d
from my3dengine.camera import Camera
from OpenGL.GL import *

class Game:
    def __init__(self):
        self.WIDTH, self.HEIGHT = m3d.get_fullscreen()
        self.window = m3d.Window("3D Game", self.WIDTH, self.HEIGHT)
        self.keys = m3d.Key
        self.escape_was_pressed = False

        self.camera = Camera(
            position=(20, 20, 50),
            target=(8, 8, 8),
            up=(0, 1, 0),
            fov=60,
            aspect=self.WIDTH / self.HEIGHT,
        )

        self.base = m3d.Mesh.from_obj("assets/untitled.obj")
        self.base.set_texture("assets/bricksx64.png")

        spacing = 1.1
        self.positions = []
        for x in range(4):
            for y in range(4):
                for z in range(4):
                    self.positions.append((x * spacing, y * spacing, z * spacing))

        # FPS counter
        self.last_fps_time = time.time()
        self.frames = 0

    def update(self, dt, window):
        self.camera.handle_input(dt, window)

        glViewport(0, 0, self.WIDTH, self.HEIGHT)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        view = self.camera.view_matrix
        proj = self.camera.projection_matrix
        view_proj = proj @ view

        # Rysujemy tę samą siatkę w wielu pozycjach
        for pos in self.positions:
            self.base.set_position(*pos)
            self.base.draw(
                cam_pos=self.camera.position,
                cam_dir=m3d.normalize(self.camera.target - self.camera.position),
                fov_deg=self.camera.fov,
                view_proj_matrix=view_proj,
                debug=False
            )

        # FPS tracking
        self.frames += 1
        current_time = time.time()
        if current_time - self.last_fps_time >= 1.0:
            print(f"FPS: {self.frames}")
            self.frames = 0
            self.last_fps_time = current_time

    def run(self):
        try:
            m3d.init()
            self.window.run(self.update)
        finally:
            self.base.destroy()

if __name__ == "__main__":
    app = Game()
    app.run()
