# src/saturn2d/core.py
import pygame
from .time import Time


class Engine:
    def __init__(self, width=800, height=600, title="Saturn2D Game", fps=60):
        pygame.init()
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption(title)

        self.clock = pygame.time.Clock()
        self.fps = fps
        self.running = False

        self.current_scene = None
        self.next_scene = None

        self.time = Time()

        # Transition variables
        self.transitioning = False
        self.transition_alpha = 0
        self.transition_speed = 300  # fade speed
        self.fade_surface = pygame.Surface((width, height))
        self.fade_surface.fill((0, 0, 0))

    def set_scene(self, scene):
        self.current_scene = scene

    def change_scene(self, new_scene):
        self.next_scene = new_scene
        self.transitioning = True
        self.transition_alpha = 0

    def _handle_transition(self, dt):
        if not self.transitioning:
            return

        # Fade out
        self.transition_alpha += self.transition_speed * dt

        if self.transition_alpha >= 255:
            self.transition_alpha = 255

            # Switch scene when fully black
            if self.next_scene:
                self.current_scene = self.next_scene
                self.next_scene = None

            # Start fading back in
            self.transition_speed = -self.transition_speed

        # Fade in finished
        if self.transition_alpha <= 0:
            self.transition_alpha = 0
            self.transition_speed = abs(self.transition_speed)
            self.transitioning = False

    def run(self):
        self.running = True

        while self.running:
            self.time.update()
            dt = self.time.delta_time

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False

                if self.current_scene:
                    self.current_scene.handle_event(event)

            if self.current_scene:
                self.current_scene.update(dt)
                self.current_scene.render(self.screen)

            # Handle transition
            self._handle_transition(dt)

            # Draw fade overlay
            if self.transitioning:
                self.fade_surface.set_alpha(int(self.transition_alpha))
                self.screen.blit(self.fade_surface, (0, 0))

            pygame.display.flip()
            self.clock.tick(self.fps)

        pygame.quit()