import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *


class Window:
    def __init__(self):
        self.title = "FELLO-Engine"
        self.width = 800
        self.height = 600
        self.is_running = False
        self.display = None
    
    def set_title(self, title):
        self.title = title
        if self.display:
            pygame.display.set_caption(title)
    
    def get_title(self):
        return self.title
    
    def set_size(self, width, height):
        self.width = width
        self.height = height
        if self.display:
            pygame.display.set_mode((width, height), DOUBLEBUF | OPENGL)
            glViewport(0, 0, width, height)
    
    def get_size(self):
        return self.width, self.height
    
    def update(self):
        if self.display:
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            
            # Setup 3D projection
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            gluPerspective(45, (self.width / self.height), 0.1, 50.0)
            
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
            
            # Apply active camera and render all game objects
            from Object import RenderAllGameObjects, ApplyActiveCamera
            ApplyActiveCamera()
            RenderAllGameObjects()
            
            pygame.display.flip()
    
    def show(self):
        if not self.display:
            pygame.init()
            self.display = pygame.display.set_mode((self.width, self.height), DOUBLEBUF | OPENGL)
            pygame.display.set_caption(self.title)
            
            # OpenGL setup
            glEnable(GL_DEPTH_TEST)
            glClearColor(0.0, 0.0, 0.0, 1.0)
    
    def close(self):
        self.is_running = False
        if self.display:
            pygame.quit()
            self.display = None
