import os
import time

import pygame as pg
from pygame.key import name
import pygame_menu as pgm

from .snake import Snake
from .food import Food

class Game:
    def __init__(self) -> None:
        self.screen_widht = 780
        self.screen_hight = 600
        self.clock = pg.time.Clock()
        pg.font.init() 
        self.font = pg.font.SysFont('arial', 72)
        self.score = 0
        self.paused = True
        self.started = False
        self.title = 'Snakessss'
        self.done = False  # Флаг главного цикла
        self.need_reset = False
        self.bg = pg.image.load(os.path.join(os.curdir, 'snake', 'img', 'bg.png'))
        self.screen = pg.display.set_mode((self.screen_widht, self.screen_hight))
        self.fps = 60
        self.set_title()
        self.menu = None
        self.snake = Snake()
        self.foods_array = []

    def game_init(self):
        pg.init()
    
    def get_menu(self):
        self.set_bg()
        self.menu = pgm.Menu('Snakessss game', 400, 300, theme=pgm.pygame_menu.themes.THEME_DARK)
        self.menu.add.button('Start new game', self.start_new_game)
        if self.started:
            self.menu.add.button('Restore game', self.restore_game)
        self.menu.add.selector('Speed', [('Slow', 40), ('Medium', 25), ('Fast', 10)], onchange=self.set_speed)
        self.menu.add.button('Exit', pgm.pygame_menu.events.EXIT)
        self.menu.mainloop(self.screen)

    def disable_menu(self):
        self.menu.disable()
 
    def set_speed(self, value, difficulty):
        self.snake.speed = difficulty
        

    def set_title(self):
        pg.display.set_caption(self.title)

    def set_bg(self):
        self.screen.blit(self.bg, (0, 0))

    def start_new_game(self):
        self.started = True
        self.paused = False
        self.disable_menu()
        self.need_reset = True

    def restore_game(self):
        self.disable_menu()
        self.paused = False

    def save_game(self):
        pass

    def load_game(self):
        pass

    def gameover(self):
        surf = self.font.render('Game over', True, (20, 20, 20))
        rect = surf.get_rect()
        rect.midtop = (390, 250)
        self.screen.blit(surf, rect)
        pg.display.flip()
        time.sleep(3)
        
        self.get_menu()
    
    def update_game_window(self):
        while len(self.foods_array) < 2:
            food = Food()
            if food.get_coords() not in self.snake.get_coords():
                self.foods_array.append(food)

        for f in self.foods_array:
            if self.snake.get_head_coords() == f.get_coords():
                self.foods_array.remove(f)
                self.snake.length += 1

        self.set_bg()
        self.snake.draw(self.screen)
        for f in self.foods_array:
            f.draw(self.screen)

        pg.display.update()
        
        
        if self.snake.impacted:
            self.gameover()
            self.started = False
     
   
    def mainloop(self): 
        while not self.done:
            if self.need_reset:
                self.snake.reset()
                self.start_new_game()
                self.need_reset = False

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.done = True
            pressed = pg.key.get_pressed()
            if pressed[pg.K_ESCAPE]:
                self.paused = False if self.paused else True
                if self.paused:
                    self.get_menu()
                    
            if pressed[pg.K_UP]: 
                if self.snake.direction != 'down':
                    self.snake.direction = 'up'
            if pressed[pg.K_DOWN]:
                if self.snake.direction != 'up':
                    self.snake.direction = 'down'
            if pressed[pg.K_LEFT]:
                if self.snake.direction != 'right':
                    self.snake.direction = 'left'
            if pressed[pg.K_RIGHT]:
                if self.snake.direction != 'left':
                    self.snake.direction = 'right' 
            
            self.update_game_window()
                
            self.clock.tick(self.fps)

if __name__ == "__main__":
    game = Game()
    game.game_init()
    game.set_title()
    game.get_menu()
    game.mainloop()
 
