import os
from curses import textpad
from time import sleep

from Snake import *
from Food import *


def game(stdscr):
    # set the cursor state
    curses.curs_set(0)
    # escape sequences generated by some keys will be interpreted by curses
    stdscr.keypad(True)
    stdscr.nodelay(0)
    # makes getch() to block for delay milliseconds, and return -1 if there is still no input at the end of that time
    stdscr.timeout(100)

    # height and width of the window
    screen_height, screen_weight = stdscr.getmaxyx()
    # a box inside of the entire screen
    box = [[2, 2], [screen_height - 2, screen_weight - 2]]
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

    # welcome message
    welcome1 = "Welcome to SNAKE!"
    stdscr.addstr(0, screen_weight // 2, welcome1)
    welcome2 = "\t\tTo start playing press one of the keyboard arrows"
    stdscr.addstr(1, screen_weight // 3, welcome2)

    # create snake at length of 2 and locate on screen
    snake_obj = Snake(screen_height - 2, screen_weight - 2)
    snake_obj.putOnScreen(stdscr)

    # initial direction
    key = stdscr.getch()
    # set direction if user pressed any arrow key
    while key not in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_DOWN, curses.KEY_UP]:
        key = stdscr.getch()
    direction = key

    # create food object on screen
    food_obj = Food(screen_height - 2, screen_weight - 2)
    food_obj.createFood(snake_obj.snake_body, box, stdscr)

    # delete welcome message
    stdscr.move(1, 0)
    stdscr.clrtoeol()
    stdscr.move(0, 0)
    stdscr.clrtoeol()

    # print score on top of screen
    score = 0
    score_text = "Score: {}".format(score)
    stdscr.addstr(1, screen_weight // 2 - len(score_text) // 2, score_text)

    # the game
    while 1:
        # get a character
        key = stdscr.getch()
        # set direction if user pressed any arrow key
        if key in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_DOWN, curses.KEY_UP]:
            direction = key

        # conditions for game over
        if (snake_obj.snake_body[0][0] in [box[0][0], box[1][0]] or
                snake_obj.snake_body[0][1] in [box[0][1], box[1][1]] or
                snake_obj.snake_body[0] in snake_obj.snake_body[1:]):
            msg = "Game Over!"
            stdscr.addstr(screen_height // 2, screen_weight // 2 - len(msg) // 2, msg)
            stdscr.nodelay(0)
            stdscr.getch()
            sleep(1)
            # curses.endwin()
            break

        # find next position of snake head
        new_head = snake_obj.move(direction)
        # make snake larger
        try:
            stdscr.addch(new_head[0], new_head[1], '#')
            snake_obj.snake_body.insert(0, new_head)
        except curses.error:
            pass

        # if snake eats food
        if snake_obj.snake_body[0] == food_obj.food_place:
            # create new food on screen
            food_obj.createFood(snake_obj.snake_body, box, stdscr)

            # +1 to score and print it
            score += 1
            score_text = "Score: {}".format(score)
            stdscr.addstr(1, screen_weight // 2 - len(score_text) // 2, score_text)

        # if snake didn't eat, make it smaller again
        else:
            stdscr.addstr(snake_obj.snake_body[-1][0], snake_obj.snake_body[-1][1], ' ')
            snake_obj.snake_body.pop()


# curses.wrapper(game)


def cleanScreen():
    # for mac and linux(here, os.name is 'posix')
    if os.name == 'posix':
        _ = os.system('clear')
    else:
        # for windows platform
        _ = os.system('cls')


def start():
    window = curses.initscr()
    game(window)
    cleanScreen()
    # pass