import pygame

class Player:
    def __init__(self, x, y, width, height, images):
        self.rect = pygame.Rect(x, y, width, height)
        self.images = images
        for image in images.keys():
            self.images[image] = pygame.transform.scale(images[image], (width, height))
        self.active_image = None
        self.flip_image = False
        self.state = "idle"
        self.sx, self.sy = 0, 0
        self.move_speed = 4
        self.gravity = 0.8
        self.jump_power = 12
        self.on_ground = False

    def update_active_image(self):
        self.active_image = self.images[self.state]

    def draw(self, screen, cx, cy):
        image = self.active_image.copy()
        if self.flip_image:
            image = pygame.transform.flip(image, True, False)
        screen.blit(image, (self.rect.x-cx, self.rect.y-cy))

    def controls(self, keys):
        self.sy += self.gravity
        self.sx = 0
        if keys[pygame.K_LEFT]:
            self.sx -= self.move_speed
            self.flip_image = False
        if keys[pygame.K_RIGHT]:
            self.sx += self.move_speed
            self.flip_image = True
        if keys[pygame.K_UP] and self.on_ground:
            self.sy = -self.jump_power

    def collision(self, _map, tile_size, solid_tiles):
        self.rect.x += self.sx
        if self.rect.x < 0:
            self.rect.x = 0
        for y in range(len(_map)):
            for x in range(len(_map[y])):
                if _map[y][x] in solid_tiles:
                    rect = pygame.Rect(x*tile_size, y*tile_size, tile_size, tile_size)
                    if rect.colliderect(self.rect):
                        if self.sx > 0:
                            self.rect.right = rect.left
                        elif self.sx < 0:
                            self.rect.left = rect.right

        self.rect.y += self.sy
        self.on_ground = False
        for y in range(len(_map)):
            for x in range(len(_map[y])):
                if _map[y][x] in solid_tiles:
                    rect = pygame.Rect(x*tile_size, y*tile_size, tile_size, tile_size)
                    if rect.colliderect(self.rect):
                        if self.sy < 0:
                            self.rect.top = rect.bottom
                            self.sy = 0
                        elif self.sy > 0:
                            self.rect.bottom = rect.top
                            self.sy = 0
                            self.on_ground = True