import pygame
import pygame_menu
import random as rand
import modules.User as User
import modules.Game_new as Game
import modules.Labels as Label
from modules.GameObject import *

pygame.init()
MAINSCREEN_SIZE = (1024,768)
MAINSCREEN = pygame.display.set_mode(MAINSCREEN_SIZE)

PLAYGROUND = pygame.Surface((1024,728))

pygame.display.set_caption("Snake_v1")

WEISS   = (255,255,255)
SCHWARZ = (0,0,0)
GRUEN = (0,255,0)
ROT = (255,0,0)

### FONTS ###

fonts = {
    "font1" : pygame.font.SysFont("times new roman", 18),
    "font2" : pygame.font.SysFont("times new roman", 26),
    "font3" : pygame.font.SysFont("times new roman", 32),
    "font4" : pygame.font.SysFont("times new roman", 48)
}
my_font = pygame.font.SysFont('times new roman', 26)
my_font2 = pygame.font.SysFont('times new roman', 32)
my_font3 = pygame.font.SysFont('times new roman', 46)

### TEXTLABELS ###
surface_text_noplayer = fonts["font2"].render("Es existiert noch kein Spieler", True, SCHWARZ)
surface_text_inputplayername = fonts["font1"].render("Bitte gib einen Namen ein: ", True, SCHWARZ)

labels = []


active = True

clock = pygame.time.Clock()

#Handles all collided objects an adds it as playerfollower

def apply_name(input):
    print(input)
    if(len(input) <= 0):
        print("Kein Name eingegeben!")
    else:
        if(User.select(input) == False):
            User.createuser(input)
        elif(User.select(input) == True):
            print("Es existiert bereits ein Spieler mit diesem Namen!")

    print(F"Hallo {User.getusername()}, dein letztes Spiel war am: {User.getlastlogin()} mit einem Highscore von: {User.gethighscore()}")

def get_text_input(dest=str):
    return dest
    

surface_menu = pygame.Surface((400, 500))
surface_menu.fill((244,244,244))
surface_menu_rect = surface_menu.get_rect()



def percent_from_screen(base:int, percent:int) -> int:

    perc_hundred = base/100

    return int(perc_hundred*percent)



game = Game.Game()
User = User.User()

input_label1 = Label.Input_Label(True, (50,50), (100,25), PLAYGROUND)
labels.append(input_label1)


player = Player("Player", PLAYGROUND, PLAYGROUND.get_size(), 100, 100, size=40)

def spawn_entities(x:int, list_of_objects:list):
    count = 0
    for y in range(x):
        rect_size = 80
        Entity = Block("Entitiy-"+str(count), MAINSCREEN, MAINSCREEN_SIZE, rand.randint(1,MAINSCREEN_SIZE[0]), rand.randint(1,MAINSCREEN_SIZE[1]), rand.randint(1,15), is_rect=True, rect_size=(rect_size,rect_size))
        Entity.get_name(True)
        list_of_objects.append(Entity)
        count += 1

fruits = [
    "data/models/fruit_1_1_scaled_2_red.png",
    "data/models/fruit_1_1_scaled_2_green.png",
    "data/models/fruit_1_1_scaled_2_yellow.png",
    "data/models/fruit_1_1_scaled_2_orange.png"
]

background = pygame.surface.Surface((640,480))

x = 3600   
invert = False

counter = 0

#Fenster-Hauptschleife

spawn_fruit = True
game_started = False
text_input_activate = True
text_input_buffer = str()

game.change_state("menu")

while active == True:   
    MAINSCREEN.fill((55,148,38))
    PLAYGROUND.fill((244,244,244))
    for event in pygame.event.get():
        #print(event)
        if (event.type == pygame.QUIT):
            print("Programm wird geschlossen!")
            #print(spawned_entities, end="\n")
            active = False
        if(game.get_state("started")):
            if (event.type == pygame.KEYDOWN):
                if (event.key == pygame.K_UP):
                    game_started = True
                    if(player.get_playermovedirection()["down"] != True):
                        player.change_direction("up")
                elif (event.key == pygame.K_DOWN):
                    game_started = True
                    if(player.get_playermovedirection()["up"] != True):
                        player.change_direction("down")
                elif (event.key == pygame.K_RIGHT):
                    game_started = True
                    if(player.get_playermovedirection()["left"] != True):
                        player.change_direction("right")
                elif (event.key == pygame.K_LEFT):
                    game_started = True
                    if(player.get_playermovedirection()["right"] != True):
                        player.change_direction("left")

        if(text_input_activate == True):
            if(event.type == pygame.KEYDOWN):
                text_input_buffer += event.unicode
                if(event.key == pygame.K_BACKSPACE): 
                    text_input_buffer = text_input_buffer[:-2]
                
                print(text_input_buffer)

        if(game.get_state("menu")):
            pass
              
    text_surface_score = my_font.render('Score: '+str(player.get_player_score()), True, (0, 0, 0))
    text_surface_player = my_font.render("Player: " + User.getusername(), True, SCHWARZ, None)
    text_test = my_font.render("Test", True, SCHWARZ, None)

    text_out = my_font.render(text_input_buffer, True, SCHWARZ, None)

    
    #input_label1.draw()
    pygame.draw.line(MAINSCREEN, SCHWARZ, (0,38), (MAINSCREEN_SIZE[0], 38), 2)

    
    PLAYGROUND.blit(text_out, (MAINSCREEN_SIZE[0]/2, MAINSCREEN_SIZE[1]/2))
    #pygame.draw.rect(surface_menu, (0,0,0), (0,0,400,500), 1, 7)
    #PLAYGROUND.blit(surface_menu, (20,20))

    if(User.checkuserdb() == False):
        PLAYGROUND.blit(surface_text_noplayer, (MAINSCREEN_SIZE[0]/2 - surface_text_noplayer.get_width()/2, 10))
        PLAYGROUND.blit(surface_text_inputplayername, (MAINSCREEN_SIZE[0]/2 - surface_text_inputplayername.get_width()/2, 40))
    
    if(game.get_state("started")):
        MAINSCREEN.blit(text_surface_score, (MAINSCREEN_SIZE[0]/2-text_surface_score.get_size()[0]/2,0))  #Paints the Scoreboard in Top/Center
        MAINSCREEN.blit(text_surface_player, (10, 0))
        
        #If spawn_fruit is True then create a fruitobject and set spawn_fruit=false
        if(spawn_fruit == True):
            fruit = Fruit("Fruit", PLAYGROUND, PLAYGROUND.get_size(), init_pos_x=rand.randint(0, PLAYGROUND.get_size()[0]-40), init_pos_y=rand.randint(0, PLAYGROUND.get_size()[1]-40), color=ROT, rect_size=40, score_points=10, sprite=fruits[rand.randint(0, len(fruits)-1)])
            spawn_fruit = False

        #Draws a fruit if a fruitobject is instanced
        if(fruit):
            fruit.draw()    
        
        player.draw()
        if(game_started == True and player.collide_self() == False):
            player.move(40)

        if(player.collide_self()):
            game_started == False
            gameovertext = my_font2.render("Game Over!", True, SCHWARZ)
            if(player.get_player_score() > User.gethighscore()):
                User.update_user_highscore(player.get_player_score())
            PLAYGROUND.blit(gameovertext, (MAINSCREEN_SIZE[0]/2-gameovertext.get_size()[0]/2, MAINSCREEN_SIZE[1]/2-gameovertext.get_size()[1]/2))

        if(player.collide_fruit(fruit.get_rect()) == True and fruit):
            player.add_body()
            player.inc_score(fruit.get_score_points())
            del fruit
            spawn_fruit=True

    MAINSCREEN.blit(PLAYGROUND, (0,40))
    pygame.display.flip()
    clock.tick(60)
pygame.quit()