import os
import random
import time

import cherrypy

from board import Board
import evaluator

"""
This is a simple Battlesnake server written in Python.
For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md
"""


class Battlesnake(object):
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        # This function is called when you register your Battlesnake on play.battlesnake.com
        # It controls your Battlesnake appearance and author permissions.
        # TIP: If you open your Battlesnake URL in browser you should see this data
        return {
            "apiversion": "1",
            "author": "dj0wns",
            "color": "#99FFFF",
            "head": "safe",
            "tail": "fat-rattle",
        }

    @cherrypy.expose
    @cherrypy.tools.json_in()
    def start(self):
        # This function is called everytime your snake is entered into a game.
        # cherrypy.request.json contains information about the game that's about to be played.
        data = cherrypy.request.json

        print("START")
        return "ok"

    @cherrypy.expose
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def move(self):
        start = time.time_ns()
        # This function is called on every turn of a game. It's how your snake decides where to move.
        # Valid moves are "up", "down", "left", or "right".
        # TODO Start Timer
        data = cherrypy.request.json

        # keep note of our snake id
        our_snake_id = data["you"]["id"]

        # initialize board from json data
        board = Board()
        board.parse_board(data["board"])
        # Calculate distances to each square for each snake
        board.calculate_snakes_distances()
        #print(board)

        # from this board, pick the best move
        time_allotted = 290000000 #nanoseconds, generously leaving 50ms over for ping
        move = evaluator.pick_best_move(board, our_snake_id, time_allotted)
        #TODO end timer
        end = time.time_ns()
        #print(f"MOVE: {move} - Time: {(end-start)/1000000}")
        return {"move": move}

    @cherrypy.expose
    @cherrypy.tools.json_in()
    def end(self):
        # This function is called when a game your snake was in ends.
        # It's purely for informational purposes, you don't have to make any decisions here.
        data = cherrypy.request.json

        print("END")
        return "ok"


if __name__ == "__main__":
    server = Battlesnake()
    cherrypy.config.update({"server.socket_host": "0.0.0.0"})
    cherrypy.config.update(
        {"server.socket_port": int(os.environ.get("PORT", "24001")),}
    )
    print("Starting Battlesnake Server...")
    cherrypy.quickstart(server)
