#!/usr/bin/env python3 
import sys
import curses
import time
from obj import snake
from obj import food
import shutil
import random
def main(stdscr):
    pontoi=0
    curses.curs_set(0)
    stdscr.nodelay(True)  # don't block waiting for key
    fidi=snake()
    y=16
    x=18
    while 1:
        rx = random.randrange(y)
        ry = random.randrange(x)
        if not [rx, ry] in fidi.kilia:
            fai=food(rx,ry)
            break

    paused =False

    running = True

    while running:
        
        kilia_set = set(map(tuple, fidi.kilia))
        boukia_set = set()

        for b in fidi.boukia:
            if b < len(fidi.kilia):
                boukia_set.add(tuple(fidi.kilia[b]))
        
        tablo = []
        for i in range(y):
            row = []
            for j in range(x):
                
                if (i, j) in kilia_set:
                    if (i, j) in boukia_set:
                        row.append("@")
                    elif [i, j]!=fidi.kilia[0]:
                        row.append("o")
                    else:
                        row.append("0")
                elif i==fai.x and j==fai.y:
                    row.append("*")
                else:
                    row.append(" ")
            tablo.append(row)

        
        stdscr.erase()

        curses.start_color()
        curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)  # X
        curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)   # Snake
        curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)     # *
        curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK)    # Score

        border = "X" * (x + 2)
        stdscr.addstr(0, 0, border, curses.color_pair(1))
        stdscr.addstr(0, len(border), "  *", curses.color_pair(3))
        stdscr.addstr(0, len(border) + 3, str(pontoi), curses.color_pair(4))

        
        for i in range(y):
            stdscr.addstr(i + 1, 0, "X", curses.color_pair(1))  
            for j, c in enumerate(tablo[i]):
                if c in ["@", "o", "0"]:
                    stdscr.addstr(i + 1, j + 1, c, curses.color_pair(2))
                elif c == "*":
                    stdscr.addstr(i + 1, j + 1, c, curses.color_pair(3))
                else:
                    stdscr.addstr(i + 1, j + 1, c)
            stdscr.addstr(i + 1, x + 1, "X", curses.color_pair(1))

        stdscr.addstr(y + 1, 0, "X" * (x + 2), curses.color_pair(1))
        #stdscr.addstr(y + 2, 0, str( fidi.kilia))      
        #stdscr.addstr(y + 3, 0, f" {fai.x}, {fai.y}")
            
        t=0.14
        stdscr.refresh()
        if fidi.dir=="up" or fidi.dir=="down":
            time.sleep(t*1.25)
        if fidi.dir=="right"or fidi.dir=="left":
            time.sleep(t)

        key=stdscr.getch()
        if key == 27:
            paused=True
            while paused:
                stdscr.addstr(y + 2, 0, "press esc to unpause \npress B to exit \npres R to restart") 
                stdscr.refresh()
                key2 = stdscr.getch()
                if key2 ==27:
                    paused=False
                if key2 ==ord('b'): 
                    paused=False 
                    running = False
                if key2 ==ord('r'): 
                    pontoi=0
                    paused=False 
                    curses.curs_set(0)
                    stdscr.nodelay(True)  # don't block waiting for key
                    fidi=snake()
                    y=16
                    x=18
                    while 1:
                        rx = random.randrange(y)
                        ry = random.randrange(x)
                        if not [rx, ry] in fidi.kilia:
                            fai=food(rx,ry)
                            break
                    
        time.sleep(0.1)
        
        if key == ord('w') and fidi.dir!="down":
            fidi.up()
        elif key == ord('s')and fidi.dir!="up":
            fidi.down()
        elif key == ord('a')and fidi.dir!="right":
            fidi.left()
        elif key == ord('d')and fidi.dir!="left":
            fidi.right()
        fidi.move()
        if [fai.x, fai.y]==fidi.kilia[0]:
            fidi.eat()
            pontoi+=1
            while 1:
                rx = random.randrange(y)
                ry = random.randrange(x)
                if not [rx, ry] in fidi.kilia:
                    fai.set_xy(rx,ry)
                    break
        kilia_set = set(map(tuple, fidi.kilia[1:]))
        if tuple(fidi.kilia[0]) in kilia_set:
            paused=True
            while paused:
                stdscr.addstr(y + 2, 0, "you lost :( \npress B to exit \npres R to restart") 
                stdscr.refresh()
                key2 = stdscr.getch()
                
                if key2 ==ord('b'): 
                    paused=False 
                    running = False
                if key2 ==ord('r'): 
                    pontoi=0
                    paused=False 
                    curses.curs_set(0)
                    stdscr.nodelay(True)  # don't block waiting for key
                    fidi=snake()
                    y=16
                    x=18
                    while 1:
                        rx = random.randrange(y)
                        ry = random.randrange(x)
                        if not [rx, ry] in fidi.kilia:
                            fai=food(rx,ry)
                            break
        


        if pontoi>=y*x-2:
            paused=True
            while paused:
                stdscr.addstr(y + 2, 0, " you woooon!!! :)\npress B to exit \npres R to restart") 
                stdscr.refresh()
                key2 = stdscr.getch()
                
                if key2 ==ord('b'): 
                    paused=False 
                    running = False
                if key2 ==ord('r'): 
                    pontoi=0
                    paused=False 
                    curses.curs_set(0)
                    stdscr.nodelay(True)  # don't block waiting for key
                    fidi=snake()
                    y=16
                    x=18
                    while 1:
                        rx = random.randrange(y)
                        ry = random.randrange(x)
                        if not [rx, ry] in fidi.kilia:
                            fai=food(rx,ry)
                            break



def pmain():
    y=16
    x=18

    cols, rows = shutil.get_terminal_size()
    MIN_COLS, MIN_ROWS =y,x
    if cols < MIN_COLS or rows < MIN_ROWS:
        print(f"Terminal too small! Need {MIN_COLS}x{MIN_ROWS}, got {cols}x{rows}")
        exit(1)
    if len(sys.argv)==1:
        curses.wrapper(main)

    elif len(sys.argv)==2:
        arg = sys.argv[1]
        if arg =="--credits":
            print("Made by nikiforos with love!\nI hope you have a nice time! :)")
        else:
            print("error, the command is snake")

    else:
        print("error, the command is snake")

pmain()
