import os
import pygame
import json
import csv


pygame.init()
screen_width = 1920
screen_height = 960
screen = pygame.display.set_mode((screen_width, screen_height))

class Wall(pygame.sprite.Sprite):
    def __init__(self, color, size, pos):
        super().__init__()
        self.image = pygame.Surface(size)
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft=pos)

# Load image for player
player_image = pygame.image.load("Player_right.png").convert_alpha()
player_image = pygame.transform.scale(player_image, (16, 16))  # Adjust player size to fit the new scale

class Player(pygame.sprite.Sprite):
    def __init__(self, color, walls):
        super().__init__()
        self.image = player_image
        self.rect = self.image.get_rect()
        self.foot_size = 15
        self.dt = 0
        self.speed_x = 1
        self.max_speed_x = 700
        self.speed_y = 1
        self.max_speed_y = 1500
        self.walls = walls

    def player_input(self, dt):
        keys = pygame.key.get_pressed()
        move_direction_x = 0
        move_direction_y = 0

        if keys[pygame.K_w]:
            move_direction_y -= 1
        if keys[pygame.K_s]:
            move_direction_y += 1
        if keys[pygame.K_a]:
            move_direction_x -= 1
        if keys[pygame.K_d]:
            move_direction_x += 1

        # Apply movement
        self.speed_x = move_direction_x * self.max_speed_x
        self.speed_y = move_direction_y * self.max_speed_y

        self.rect.x += self.speed_x * dt
        self.rect.y += self.speed_y * dt


# Get the directory of the current script
script_dir = os.path.dirname(__file__)

# Initialize Pygame


# Set up the display

pygame.display.set_caption('Medival Guns')

# Load JSON data
with open(os.path.join(script_dir, 'data.json')) as json_file:
    level_data = json.load(json_file)

# Load Collisions
collisions = []
with open(os.path.join(script_dir, 'Collisions.csv'), 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        # Convert non-empty strings to integers, skip empty strings
        row_data = [int(cell) if cell else 0 for cell in row]
        collisions.append(row_data)


#WALLS
walls_group = pygame.sprite.Group()

for i, row in enumerate(collisions):
    for j, el in enumerate(row):
        if el:
            walls_group.add(Wall("purple", (60, 60), (60*j, 60*i)))

#collision functioning
    def collision(self):
        collisions = pygame.sprite.spritecollide(self, self.walls, False)
        if collisions:
            for wall in collisions:
                if abs(self.rect.bottom - wall.rect.top) < self.foot_size:
                    self.rect.bottom = wall.rect.top
                    self.speed_y = 0
                    self.jumping_time = 0
                    self.is_jumping = False

                elif abs(self.rect.top - wall.rect.bottom) < self.foot_size:
                    self.rect.top = wall.rect.bottom
                    self.speed_y = 0

                elif abs(self.rect.right - wall.rect.left) < self.foot_size:
                    self.rect.right = wall.rect.left
                    self.speed_x = 0
                elif abs(self.rect.left - wall.rect.right) < self.foot_size:
                    self.rect.left = wall.rect.right
                    self.speed_x = 0

# Load images for LAYERS
layers = {}
for layer in level_data["layers"]:
    layers[layer] = pygame.image.load(layer).convert_alpha()
    layers[layer] = pygame.transform.scale(layers[layer], (screen_width, screen_height))

# Main game loop
running = True
clock = pygame.time.Clock()
dt = 0

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

    # Draw layers
    for layer_name, layer_image in layers.items():
        screen.blit(layer_image, (0, 0))

    #Draw walls
    walls_group.draw(screen)    

    # Update the display
    pygame.display.flip()

    dt = clock.tick(60) / 1000  # Get time passed since last tick in seconds

# Quit Pygame
pygame.quit()
