import pygame
import pytmx
import math

# Constants
BACKGROUND = (20, 20, 20)
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
MAP_COLLISION_LAYER = 1

# Pygame setup
pygame.init()
pygame.display.set_caption("Survive the vawe")
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
running = True


class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        # Load the idle image
        self.idle_image = pygame.image.load("Sprites/Idle/Player_right.png").convert_alpha()
        self.image = self.idle_image
        
        self.rect = self.image.get_rect(topleft=pos)  # Adjust rect to match the image size
        self.direction = pygame.math.Vector2()
        self.speed = 1.6
        self.time = 0

        # Health
        self.current_health = 1000
        self.maximum_health = 1000
        self.health_bar_length = 500
        self.health_ratio = self.maximum_health / self.health_bar_length
        self.target_health = 1000
        self.health_change_speed = 5

        # Shooting
        self.can_shoot = True
        self.shoot_cooldown_time = 100  # Milliseconds
        self.shoot_cooldown = 0

        # Animations
        self.image_direction = 1
        self.animation_timer = 0
        self.current_sprite = 0
        self.running_sprites = []
        for i in range(6):
            sprite = pygame.image.load(f"Sprites/Running/Player_run_right_{i + 1}.png").convert_alpha()
            self.running_sprites.append(sprite)

    def get_damage(self, amount):
        if self.target_health > 0:
            self.target_health -= amount
        if self.target_health <= 0:
            self.target_health = 0

    def get_health(self, amount):
        if self.target_health < self.maximum_health:
            self.target_health += amount
        if self.target_health >= self.maximum_health:
            self.target_health = self.maximum_health

    def health_bar(self):
        self.current_health += (self.target_health - self.current_health) / 10

        # Define smaller health bar dimensions
        health_bar_width = self.current_health / self.health_ratio
        health_bar_height = 10  # Set the height of the health bar

        # Adjust the position of the health bar
        health_bar_x = 10
        health_bar_y = 10

        if self.current_health > self.target_health:
            health_bar_width = self.target_health / self.health_ratio

        # Draw the health bar with adjusted dimensions and position
        health_bar_rect = pygame.Rect(health_bar_x, health_bar_y, health_bar_width, health_bar_height)
        pygame.draw.rect(screen, (255, 0, 0), health_bar_rect)  # Draw health bar in red


    def input(self):
        keys = pygame.key.get_pressed()
        speed_multiplier_x = 0
        speed_multiplier_y = 0

        if keys[pygame.K_w]:
            speed_multiplier_y = -1
        elif keys[pygame.K_s]:
            speed_multiplier_y = 1

        if keys[pygame.K_a]:
            speed_multiplier_x = -1
        elif keys[pygame.K_d]:
            speed_multiplier_x = 1

        self.direction.y = (keys[pygame.K_s]) - (keys[pygame.K_w])
        self.direction.x = (keys[pygame.K_d]) - (keys[pygame.K_a])

        if self.direction.x != 0 and self.direction.y != 0:
            self.direction.normalize_ip()

        self.direction.x *= self.speed
        self.direction.y *= self.speed

        if pygame.mouse.get_pressed()[0] and self.can_shoot:
            direction = -(pygame.math.Vector2(self.rect.topleft) - pygame.mouse.get_pos())
            direction = pygame.math.Vector2.normalize(direction)
            new_projectile = Projectile(self.rect.center, direction)
            self.can_shoot = False
            self.shoot_cooldown = pygame.time.get_ticks()

    def update(self, level):
        self.input()
        self.health_bar()
        self.rect.center += self.direction * self.speed

        # Move the screen if the player reaches the screen bounds
        if self.rect.right >= SCREEN_WIDTH - 200:
            difference = self.rect.right - (SCREEN_WIDTH - 200)
            self.rect.right = SCREEN_WIDTH - 200
            level.shift_level(-difference, 0)
        
        if self.rect.left <= 200:
            difference = 200 - self.rect.left
            self.rect.left = 200
            level.shift_level(difference, 0)
        
        if self.rect.top <= 200:
            difference = 200 - self.rect.top
            self.rect.top = 200
            level.shift_level(0, difference)

        if self.rect.bottom >= SCREEN_HEIGHT - 200:
            difference = self.rect.bottom - (SCREEN_HEIGHT - 200)
            self.rect.bottom = SCREEN_HEIGHT - 200
            level.shift_level(0, -difference)

        self.check_collision(level)

        now = pygame.time.get_ticks()
        if now - self.shoot_cooldown > self.shoot_cooldown_time:
            self.can_shoot = True

        if now - self.animation_timer > 50:
            if pygame.Vector2.length(self.direction) == 0:
                self.image = self.idle_image
                self.current_sprite = 0
            else:
                self.animation_timer = pygame.time.get_ticks()
                self.current_sprite += 1
                if self.current_sprite > len(self.running_sprites) - 1:
                    self.current_sprite = 0
                self.image = self.running_sprites[self.current_sprite]
                if self.direction.x < 0:  # If moving left, flip the image
                    self.image = pygame.transform.flip(self.image, True, False)

    def check_collision(self, level):
        for layer in level.layers:
            if layer.index == MAP_COLLISION_LAYER:
                for tile in layer.tiles:
                    if self.rect.colliderect(tile.rect):
                        self.rect.center -= self.direction * self.speed
                        return


class Projectile(pygame.sprite.Sprite):
    def __init__(self, pos, direction):
        super().__init__()
        self.image = pygame.image.load("Sprites/bullet.png").convert_alpha()
        self.image_direction = 1

        self.direction = direction
        self.speed = 15
        angle = math.degrees(math.atan2(-self.direction.y, self.direction.x))

        self.image = pygame.transform.rotate(self.image, angle)
        self.rect = self.image.get_rect(center=pos)
        self.rect.center += self.direction * 50

        self.life_timer = 10000  # Milliseconds
        self.spawned_time = pygame.time.get_ticks()

    def collision(self):
        pass  # Removed the collision logic for simplicity

    def update(self):
        self.rect.center += self.direction * self.speed
        self.collision()

        now = pygame.time.get_ticks()
        if now - self.spawned_time > self.life_timer:
            self.kill()


class Game:
    def __init__(self):

        self.currentLevelNumber = 0
        self.levels = []
        self.levels.append(Level(fileName="resources/level1.tmx"))
        self.currentLevel = self.levels[self.currentLevelNumber]

    def draw(self):
        screen.fill(BACKGROUND)
        self.currentLevel.draw()

        player_group.draw(screen)  # Draw player sprite
        pygame.display.flip()


class Level:
    def __init__(self, fileName):
        self.mapObject = pytmx.load_pygame(fileName)
        self.layers = []
        for layer in range(len(self.mapObject.layers)):
            self.layers.append(Layer(index=layer, mapObject=self.mapObject))

    def draw(self):
        for layer in self.layers:
            layer.draw()

    def shift_level(self, x_amount, y_amount):
        for layer in self.layers:
            for tile in layer.tiles:
                tile.rect.x += x_amount
                tile.rect.y += y_amount


class Layer:
    def __init__(self, index, mapObject):
        self.index = index
        self.tiles = pygame.sprite.Group()
        self.mapObject = mapObject
        for x in range(self.mapObject.width):
            for y in range(self.mapObject.height):
                img = self.mapObject.get_tile_image(x, y, self.index)
                if img:
                    self.tiles.add(Tile(image=img, x=(x * self.mapObject.tilewidth), y=(y * self.mapObject.tileheight)))

    def draw(self):
        for tile in self.tiles:
            screen.blit(tile.image, tile.rect)


class Tile(pygame.sprite.Sprite):
    def __init__(self, image, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y


# Main game setup
game = Game()
player = Player((100, 200))  # Update player spawn coordinates
player_group = pygame.sprite.Group()  # Create a sprite group for the player
player_group.add(player)  # Add the player sprite to the group


# Main game loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player.get_health(200)
            elif event.key == pygame.K_DOWN:
                player.get_damage(200)

    game.draw()
    player.update(game.currentLevel)
    pygame.display.flip()
    clock.tick(60)
