# Text Adventure -- main loop (finished).
#
# Run from this folder:
#   cd projects/04-text-adventure/finished
#   python main.py

import world

current_room_id = world.start_id
inventory = []

def describe(room):
    print(f"-- {room['name']} --")
    print(room["description"])
    if len(room["items"]) > 0:
        print("Items here: " + ", ".join(room["items"]))
    exit_names = list(room["exits"].keys())
    print("Exits: " + ", ".join(exit_names))

def go(direction):
    global current_room_id
    room = world.rooms[current_room_id]
    next_id = room["exits"].get(direction)
    if next_id is None:
        print("You cannot go that way.")
        return
    current_room_id = next_id
    describe(world.rooms[current_room_id])

def take(item_name):
    room = world.rooms[current_room_id]
    for i, item in enumerate(room["items"]):
        if item == item_name:
            room["items"].pop(i)
            inventory.append(item)
            print(f"You pick up the {item}.")
            if item == "gold coin":
                print("You found the treasure! You win!")
                return True
            return False
    print(f"There is no {item_name} here.")
    return False

def show_inventory():
    if len(inventory) == 0:
        print("You are carrying nothing.")
        return
    print("You are carrying: " + ", ".join(inventory))

def parse(line):
    words = line.split()
    if not words:
        return None, None
    verb = words[0]
    arg = words[1] if len(words) > 1 else None
    if len(words) > 2:
        arg = " ".join(words[1:])
    return verb, arg

describe(world.rooms[current_room_id])

while True:
    try:
        line = input("> ")
    except EOFError:
        break

    verb, arg = parse(line)

    if verb is None:
        # empty line, do nothing
        pass
    elif verb == "look":
        describe(world.rooms[current_room_id])
    elif verb == "go":
        if arg is None:
            print("Go where?")
        else:
            go(arg)
    elif verb == "take":
        if arg is None:
            print("Take what?")
        else:
            won = take(arg)
            if won:
                break
    elif verb in ("inv", "inventory"):
        show_inventory()
    elif verb == "quit":
        print("Goodbye.")
        break
    else:
        print(f"I do not understand '{verb}'.")
