import pygame
class PhysicsEntity:
    def __init__(self, game, e_type, pos:tuple, size):
        self.game = game
        self.e_type = e_type
        self.pos = list(pos)
        self.size = size
        self.velocity = [0,0]
        self.collisions = {"top":False, "bottom":False, "left":False, "right":False}
        self.speed = 3
        
    def update(self, tilemap, movement:tuple=(0,0)):
        self.collisions = {"top":False, "bottom":False, "left":False, "right":False}
        frame_movement = ((movement[0] + self.velocity[0])*self.speed, movement[1] + self.velocity[1])
        self.pos[0] += frame_movement[0]

        entity_rect = self.rect()
        for recto in tilemap.physics_rects_around(self.pos):
            if entity_rect.colliderect(recto):
                if frame_movement[0] > 0:
                    entity_rect.right = recto.left
                    self.collisions["right"] = True
                    self.game.isJumping = False


                if frame_movement[0] < 0:
                    entity_rect.left = recto.right
                    self.collisions["left"] = True
                    self.game.isJumping = False


                self.pos[0] = entity_rect.x
        
        self.pos[1] += frame_movement[1]
        entity_rect = self.rect()

        for rectolino in tilemap.physics_rects_around(self.pos):
            if entity_rect.colliderect(rectolino):

                if frame_movement[1] > 0:
                    entity_rect.bottom = rectolino.top
                    self.collisions["bottom"] = True
                    self.game.isJumping = False

                if frame_movement[1] < 0:
                    entity_rect.top = rectolino.bottom
                    self.collisions["top"] = True

                self.pos[1] = entity_rect.y
        
        if self.collisions['bottom'] or self.collisions['top']:
            self.velocity[1] = 0


        self.velocity[1] = min(5, self.velocity[1] + 0.1)

    def render(self, surface:pygame.Surface, offset:tuple=(0,0)):
        surface.blit(self.game.assets["player"], (self.pos[0]-offset[0], self.pos[1]-offset[1]))
        
    def rect(self):
        return pygame.Rect(self.pos[0], self.pos[1], self.size[0], self.size[1])