import pygame
from random import randint
import math

# pygame setup
pygame.init()
pygame.display.set_caption("Vampire survivors")
screen = pygame.display.set_mode((1920, 1015))
clock = pygame.time.Clock()
running = True

class Player(pygame.sprite.Sprite):
    def __init__(self, pos, group, pos_x, pos_y):
        super().__init__(group)

        self.direction = pygame.math.Vector2()
        self.speed = 2.5

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

        #sprites right
        self.sprites_right = []
        self.in_animation = False
        self.side = True
        self.sprites_right.append(pygame.image.load("Sprites/Idle/Player_right.png"))
        self.sprites_right.append(pygame.image.load("Sprites/Running/Player_run_right_1.png"))
        self.sprites_right.append(pygame.image.load("Sprites/Running/Player_run_right_2.png"))
        self.sprites_right.append(pygame.image.load("Sprites/Running/Player_run_right_3.png"))
        self.sprites_right.append(pygame.image.load("Sprites/Running/Player_run_right_4.png"))
        self.sprites_right.append(pygame.image.load("Sprites/Running/Player_run_right_5.png"))
        self.sprites_right.append(pygame.image.load("Sprites/Running/Player_run_right_6.png"))
        self.current_sprite_right = 0
        self.image = self.sprites_right[self.current_sprite_right]
        self.rect = self.image.get_rect(center = pos)

        self.rect = self.image.get_rect()
        self.rect.topleft = [pos_x,pos_y]


        #sprites left
        self.sprites_left = []
        self.in_animation_2 = False
        self.sprites_left.append(pygame.image.load("Sprites/Idle/Player_left.png"))
        self.sprites_left.append(pygame.image.load("Sprites/Running/Player_run_left_1.png"))
        self.sprites_left.append(pygame.image.load("Sprites/Running/Player_run_left_2.png"))
        self.sprites_left.append(pygame.image.load("Sprites/Running/Player_run_left_3.png"))
        self.sprites_left.append(pygame.image.load("Sprites/Running/Player_run_left_4.png"))
        self.sprites_left.append(pygame.image.load("Sprites/Running/Player_run_left_5.png"))
        self.sprites_left.append(pygame.image.load("Sprites/Running/Player_run_left_6.png"))
        self.current_sprite_left = 0
        self.image = self.sprites_left[self.current_sprite_left]

        self.rect = self.image.get_rect()
        self.rect.topleft = [pos_x,pos_y]

    
    def animate_right(self, start):
        self.in_animation = start

    def animate_left(self, start):
        self.in_animation_2 = start

    def sides(self, start):
        self.side = start


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

        if keys[pygame.K_w] or keys[pygame.K_UP]:
            speed_multiplier_y = -1
        elif keys[pygame.K_s] or keys[pygame.K_DOWN]:
            speed_multiplier_y = 1
    
   # Check if A and D keys are pressed
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            speed_multiplier_x = -1
        elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            speed_multiplier_x = 1

         # Calculate movement direction based on keys pressed
        self.direction.x = speed_multiplier_x
        self.direction.y = speed_multiplier_y


        self.direction.y = (keys[pygame.K_DOWN] or keys[pygame.K_s]) - (keys[pygame.K_UP] or keys[pygame.K_w])
        self.direction.x = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or 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() - camera_group.offset)
                    direction = pygame.math.Vector2.normalize(direction)
                    new_projectile = Projectile(self.rect.center, direction, camera_group)
                    self.can_shoot = False
                    self.shoot_cooldown = pygame.time.get_ticks()

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

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

        # Animation for moving right
        if self.direction.x > 0:
            self.animate_right(True)
            self.animate_left(False)
            self.side = True
            self.image = self.sprites_right[int(self.current_sprite_right)]
            self.current_sprite_right = (self.current_sprite_right + 0.2) % len(self.sprites_right)
        # Animation for moving left
        elif self.direction.x < 0:
            self.animate_left(True)
            self.animate_right(False)
            self.side = False
            self.image = self.sprites_left[int(self.current_sprite_left)]
            self.current_sprite_left = (self.current_sprite_left + 0.2) % len(self.sprites_left)

        elif self.direction.y > 0:
            if self.side == True:
                self.animate_right(True)
                self.animate_left(False)
                self.image = self.sprites_right[int(self.current_sprite_right)]
                self.current_sprite_right = (self.current_sprite_right + 0.2) % len(self.sprites_right)
            elif self.side == False:
                self.animate_right(False)
                self.animate_left(True)
                self.image = self.sprites_left[int(self.current_sprite_left)]
                self.current_sprite_left = (self.current_sprite_left + 0.2) % len(self.sprites_left)
        elif self.direction.y < 0:
            if self.side == True:
                self.animate_right(True)
                self.animate_left(False)
                self.image = self.sprites_right[int(self.current_sprite_right)]
                self.current_sprite_right = (self.current_sprite_right + 0.2) % len(self.sprites_right)
            elif self.side == False:
                self.animate_right(False)
                self.animate_left(True)
                self.image = self.sprites_left[int(self.current_sprite_left)]
                self.current_sprite_left = (self.current_sprite_left + 0.2) % len(self.sprites_left)
    
        # Idle animation when not moving
        else:
            self.animate_right(False)
            self.animate_left(False)
            # Set the idle sprite based on the last direction
            if self.side:
                self.image = self.sprites_right[0]
            else:
                self.image = self.sprites_left[0]
       

        

class Projectile(pygame.sprite.Sprite):
    def __init__(self, pos, direction, group):
        super().__init__(group)
        self.image = pygame.image.load("Sprites/bullet.png").convert_alpha()
        
        self.direction = direction
        self.speed = 10
        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.life_timer = 10000 # Milliseconds
        self.spawned_time = pygame.time.get_ticks()

    def collision(self):
        for enemy in enemies:
            distance = pygame.math.Vector2.length(pygame.math.Vector2(enemy.rect.center) - self.rect.center)
            if distance < 20:
                self.kill()
                enemy.damage(1)
                break

    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 Enemy(pygame.sprite.Sprite):
    def __init__(self, pos, group):
        super().__init__(group)
        self.image = pygame.surface.Surface((20, 20))
        self.image.fill("black")
        self.rect = self.image.get_rect(center = pos)
        self.direction = pygame.math.Vector2()
        self.speed = 1
        self.enemy_count = 0

    def damage(self, damage):
        enemies.remove(self)
        self.enemy_count -= 1
        self.kill()


    def update(self):
        self.direction = pygame.math.Vector2(player.rect.center) - self.rect.center
        if(pygame.math.Vector2.length(self.direction)<20):
            self.kill()
        self.direction = pygame.math.Vector2.normalize(self.direction)
        self.rect.center += self.direction * self.speed

class CameraGroup(pygame.sprite.Group):
    def __init__(self):
        super().__init__()
        self.display_surface = pygame.display.get_surface()

        self.offset = pygame.math.Vector2(300, 100)
        self.half_w = self.display_surface.get_size()[0] // 2
        self.half_h = self.display_surface.get_size()[1] // 2

    def center_target_camera(self, target):
        self.offset.x = target.rect.centerx - self.half_w
        self.offset.y = target.rect.centery - self.half_h

    def custom_draw(self, player):
        self.center_target_camera(player)

        for sprite in sorted(self.sprites(), key=lambda sprite: sprite.rect.centery):
            offset_pos = sprite.rect.topleft - self.offset
            self.display_surface.blit(sprite.image, offset_pos)

def spawn_enemy():
    random_x = randint(-1000, 1000)
    random_y = randint(-1000, 1000)
    enemies.append(Enemy((player.rect.centerx + random_x, player.rect.centery + random_y), camera_group))

spawn_enemy_event = pygame.USEREVENT + 1
#Setup
camera_group = CameraGroup()
enemies = []

player = Player((500, 500), camera_group, 10, 10)
pygame.time.set_timer(spawn_enemy_event, 100)

for i in range(10):
    spawn_enemy()

crosshair_img = pygame.transform.scale(pygame.image.load('Sprites/crosshair.png'), (30, 30))
cursor = pygame.cursors.Cursor((0, 0), crosshair_img)
pygame.mouse.set_cursor(cursor)
pygame.mouse.set_visible(True | False)

while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        if e.type == spawn_enemy_event:
            spawn_enemy()

    screen.fill("cyan")
    
    camera_group.update()
    camera_group.custom_draw(player)

    pygame.display.flip()

    clock.tick(60)

pygame.quit()