import os
import time

import pygame as pg
import pygame_menu

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 = []
        self.game_speed = 0

    def game_init(self):
        pg.init()
    
    def get_menu(self):
        self.set_bg()
        self.menu = pygame_menu.Menu('Snakessss game', 400, 300, theme=pygame_menu.themes.THEME_BLUE)
        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', 0), ('Medium', 1), ('Fast', 2)], onchange=self.set_speed, onreturn=self.restore_game)
        self.menu._widgets[-1].set_value(self.game_speed)
        self.menu.add.button('Exit', pygame_menu.events.EXIT)
        self.menu.mainloop(self.screen)

    def disable_menu(self):
        if self.menu is not None:
            self.menu.disable()
 
    def set_speed(self, tuple_celected, difficulty):
        self.game_speed = difficulty
        self.snake.set_speed(speed=self.game_speed)
        
    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):
        print(self.game_speed, self.snake.speed)
        self.started = True
        self.paused = False
        self.disable_menu()
        self.need_reset = True

    def restore_game(self, *args, **kwargs):
        if self.started:
            self.disable_menu()
            self.paused = False
        else:
            self.start_new_game()


    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()
        score = self.font.render(f'Score: {self.score}', True, (20, 20, 20))
        rect2 = score.get_rect()
        rect.midtop = (390, 250)
        rect2.midtop = (390, 320)
        self.screen.blit(surf, rect)
        self.screen.blit(score, rect2)
        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.score += 5 * self.snake.length
                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.started = False
            self.gameover()
     
   
    def mainloop(self): 
        while not self.done:
            if self.need_reset:
                self.snake.reset(speed=self.game_speed)
                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()
 
