from room import Room
from player import Player
from world import World

import random
from ast import literal_eval
from util import Queue, Stack


# Load world
world = World()


# You may uncomment the smaller graphs for development and testing purposes.
# map_file = "maps/test_line.txt"
# map_file = "maps/test_cross.txt"
# map_file = "maps/test_loop.txt"
# map_file = "maps/test_loop_fork.txt"
map_file = "maps/main_maze.txt"

# Loads the map into a dictionary
room_graph=literal_eval(open(map_file, "r").read())
print(len(room_graph))
world.load_graph(room_graph)

# Print an ASCII map
world.print_rooms()

player = Player(world.starting_room)
########################################################################################################################
# Fill this out with directions to walk
# traversal_path = ['n', 'n']
traversal_path = []
visited = {}
backtrack = []
reverse_d = {"n": "s", "s": "n", "e": "w", "w": "e"}
#add first entry to counter error
visited[0] = player.current_room.get_exits()
#print(visited[0])
#
#stack = Stack()
#stack.push(player.current_room.id)

#run until every room is visited
while len(visited) != len(room_graph)-1:


    if player.current_room.id not in visited:
        #log the exit values to the key aka unvisited room direction
        visited[player.current_room.id] = player.current_room.get_exits()
        #don't need the direction from the room we came from because it been visited
        visited[player.current_room.id].remove(backtrack[-1])

    #dead end reach, go back a room until a room with connections is reached
    #if in a "hallway" keep going back
    #check dictionary key,value if there are rooms to visit
    while len(visited[player.current_room.id]) == 0:
        goback = backtrack.pop()
        player.travel(goback)
        traversal_path.append(goback)


    #get the last direction from the path
    not_visited_direction = visited[player.current_room.id].pop()
    traversal_path.append(not_visited_direction)
    backtrack.append(reverse_d[not_visited_direction])
    player.travel(not_visited_direction)










# # TRAVERSAL TEST - DO NOT MODIFY
visited_rooms = set()
player.current_room = world.starting_room
visited_rooms.add(player.current_room)

for move in traversal_path:
    player.travel(move)
    visited_rooms.add(player.current_room)

if len(visited_rooms) == len(room_graph):
    print(f"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited")
else:
    print("TESTS FAILED: INCOMPLETE TRAVERSAL")
    print(f"{len(room_graph) - len(visited_rooms)} unvisited rooms")



#######
# UNCOMMENT TO WALK AROUND
#######
# player.current_room.print_room_description(player)
# while True:
#     cmds = input("-> ").lower().split(" ")
#     if cmds[0] in ["n", "s", "e", "w"]:
#         player.travel(cmds[0], True)
#     elif cmds[0] == "q":
#         break
#     else:
#         print("I did not understand that command.")
