# src/saturn2d/entity.py
import pygame

class Entity:
    def __init__(self, x=0, y=0, width=32, height=32, sprite=None):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.sprite = sprite
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def handle_event(self, event):
        pass

    def update(self, dt, obstacles=None):
        self.rect.topleft = (self.x, self.y)

    def render(self, screen, camera=None):
        draw_x, draw_y = self.x, self.y
        if camera:
            draw_x -= camera.x
            draw_y -= camera.y
        if self.sprite:
            screen.blit(self.sprite, (draw_x, draw_y))
        else:
            pygame.draw.rect(screen, (255, 255, 255), (draw_x, draw_y, self.width, self.height))

    def collides_with(self, other):
        return self.rect.colliderect(other.rect)


class Player(Entity):
    def __init__(self, x, y, width=32, height=32, sprite=None, speed=200):
        super().__init__(x, y, width, height, sprite)
        self.speed = speed
        self.is_player = True

    def update(self, dt, obstacles=None):
        keys = pygame.key.get_pressed()
        dx = dy = 0
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            dx -= self.speed * dt
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            dx += self.speed * dt
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            dy -= self.speed * dt
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            dy += self.speed * dt

        # Horizontal movement & collision
        self.x += dx
        self.rect.topleft = (self.x, self.y)
        if obstacles:
            for o in obstacles:
                if self.collides_with(o):
                    if dx > 0:
                        self.x = o.rect.left - self.width
                    elif dx < 0:
                        self.x = o.rect.right
                    self.rect.topleft = (self.x, self.y)

        # Vertical movement & collision
        self.y += dy
        self.rect.topleft = (self.x, self.y)
        if obstacles:
            for o in obstacles:
                if self.collides_with(o):
                    if dy > 0:
                        self.y = o.rect.top - self.height
                    elif dy < 0:
                        self.y = o.rect.bottom
                    self.rect.topleft = (self.x, self.y)


class Rectangle(Entity):
    def __init__(self, x, y, width, height, color=(255, 255, 255)):
        super().__init__(x, y, width, height)
        self.color = color

    def render(self, screen, camera=None):
        draw_x, draw_y = self.x, self.y
        if camera:
            draw_x -= camera.x
            draw_y -= camera.y
        pygame.draw.rect(screen, self.color, (draw_x, draw_y, self.width, self.height))