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

local world = require("world")

local current_room_id = world.start_id
local inventory = {}

local function describe(room)
    print("-- " .. room.name .. " --")
    print(room.description)
    if #room.items > 0 then
        print("Items here: " .. table.concat(room.items, ", "))
    end
    local exit_names = {}
    for direction, _ in pairs(room.exits) do
        table.insert(exit_names, direction)
    end
    print("Exits: " .. table.concat(exit_names, ", "))
end

local function go(direction)
    local room = world.rooms[current_room_id]
    local next_id = room.exits[direction]
    if next_id == nil then
        print("You cannot go that way.")
        return
    end
    current_room_id = next_id
    describe(world.rooms[current_room_id])
end

local function take(item_name)
    local room = world.rooms[current_room_id]
    for i, item in ipairs(room.items) do
        if item == item_name then
            table.remove(room.items, i)
            table.insert(inventory, item)
            print("You pick up the " .. item .. ".")
            if item == "gold coin" then
                print("You found the treasure! You win!")
                return true
            end
            return false
        end
    end
    print("There is no " .. item_name .. " here.")
    return false
end

local function show_inventory()
    if #inventory == 0 then
        print("You are carrying nothing.")
        return
    end
    print("You are carrying: " .. table.concat(inventory, ", "))
end

local function parse(input)
    local words = {}
    for w in string.gmatch(input, "%S+") do
        table.insert(words, w)
    end
    local verb = words[1]
    local arg = words[2]
    if #words > 2 then
        arg = table.concat(words, " ", 2)
    end
    return verb, arg
end

describe(world.rooms[current_room_id])

while true do
    io.write("> ")
    local input = io.read()
    if input == nil then break end

    local verb, arg = parse(input)

    if verb == nil then
        -- empty line, do nothing
    elseif verb == "look" then
        describe(world.rooms[current_room_id])
    elseif verb == "go" then
        if arg == nil then
            print("Go where?")
        else
            go(arg)
        end
    elseif verb == "take" then
        if arg == nil then
            print("Take what?")
        else
            local won = take(arg)
            if won then break end
        end
    elseif verb == "inv" or verb == "inventory" then
        show_inventory()
    elseif verb == "quit" then
        print("Goodbye.")
        break
    else
        print("I do not understand '" .. verb .. "'.")
    end
end
