import pygame
from random import randint
from apple import Apple
from settings import Settings
from snake import Snake
from settings import Direction
import time

pygame.init()

width = Settings.SCREEN_WIDTH.value
height = Settings.SCREEN_HEIGHT.value

# okno gry
window = pygame.display.set_mode((width, height))

def set_background():
    screen = pygame.Surface((width, height))
    original_img = pygame.image.load('background.png')

    for row in range(0, width, 32):
        for col in range(0, height, 32):
            img = original_img.copy()
            mask = (randint(0, 20), randint(0, 20), randint(0, 20))

            img.fill(mask, special_flags=pygame.BLEND_ADD)

            screen.blit(img, (row, col))

    return screen

def print_info(text):
    my_font = pygame.font.SysFont("Arial", 30, bold=True, italic=False)
    point_info = my_font.render(f"Points: {text}", False, (0, 0, 0))
    return point_info

running = True
bg_window = set_background()
apple = Apple()
apples = pygame.sprite.Group(apple)

points = 0

timer = pygame.time.Clock()

snake = Snake()
MOVE_SNAKE = pygame.USEREVENT + 1
pygame.time.set_timer(MOVE_SNAKE, 200)

while running:

    for event in pygame.event.get():

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                snake.change_direction(Direction.UP)
            if event.key == pygame.K_s:
                snake.change_direction(Direction.DOWN)
            if event.key == pygame.K_d:
                snake.change_direction(Direction.RIGHT)
            if event.key == pygame.K_a:
                snake.change_direction(Direction.LEFT)

        elif event.type == MOVE_SNAKE:
            snake.update()
    
        elif event.type == pygame.QUIT:
            running = False

    window.blit(bg_window, (0, 0))

    window.blit(print_info(points), (32, 32))

    window.blit(snake.snake_img, snake.snake_rect)

    # rysujemy segmenty
    for segment in snake.body:
        window.blit(snake.body_img, segment)

    # rysujemy jabłko
    for a in apples:
        window.blit(apple.img_apple, apple.rect)

    # kolizja z jabłkiem (dodanie segmentu do body)
    if snake.snake_rect.colliderect(apple.rect):
        snake.add_segemnt()
        points += 1
        apple = Apple()
        apples = pygame.sprite.Group(apple)

    # sprawdzenie ograniczenia 
    if not snake.border_boundary():
        time.sleep(2)
        running = False

    pygame.display.flip()
    timer.tick(30)

pygame.quit()
quit()