-- TODO:
--  -Localize everything
--  -Better interface for selecting home location
--  -Multiple home locations -> multiple keybinds?

HomePort = {}
HomePort.name = "HomePort"
HomePort.default_vars = { home1 = nil, home2 = nil, home3 = nil, home4 = nil, home5 = nil }
HomePort.version = 1

local function parseOptions (option)
    -- Taken from http://wiki.esoui.com/How_to_add_a_slash_command
    local options = {}
    local word
    for word in string.gmatch(option, "%w+") do table.insert(options, word) end
    return options
end

function HomePort.Choose(options)
    if options == nil then
        -- we're using a hotkey to get here, don't crash!
        options = {}
    else
        -- l2typecheck
        options = parseOptions(options)
    end

    local function getNumberAndNode(option)
        local home = nil
        if tonumber(option) ~= nil then
            home = tonumber(option)
        end

        if home < 1 or home > 5 then
            home = nil
        end

        local node = nil

        if home == 1 then
            node = HomePort.savedVariables.home1
        elseif home == 2 then
            node = HomePort.savedVariables.home2
        elseif home == 3 then
            node = HomePort.savedVariables.home3
        elseif home == 4 then
            node = HomePort.savedVariables.home4
        elseif home == 5 then
            node = HomePort.savedVariables.home5
        end

        return home, node
    end

    if #options == 0 or (#options == 1 and tonumber(options[1]) ~= nil) then
        local home, node = getNumberAndNode(options[1])

        if home == nil then
            CHAT_SYSTEM:AddMessage(options[1] .. " is not a valid saved location number!")
            return
        end

        -- do that thing that we do
        if node == nil then
            CHAT_SYSTEM:AddMessage("You don't have a saved home location for " .. home .. ".")
        else
            local n_known, n_name = GetFastTravelNodeInfo(node)
            local cur_node = ZO_Map_GetFastTravelNode()

            if cur_node == node then
                CHAT_SYSTEM:AddMessage("We're already at " .. n_name .. "!")
                return
            end

            if cur_node == nil then
                CHAT_SYSTEM:AddMessage("WARNING: Following port will cost " .. GetRecallCost() .. "g! Move or hit escape to cancel.")
            end

            CHAT_SYSTEM:AddMessage("Porting to " .. n_name .. "!")
            FastTravelToNode(node)
        end
        return
    end

    local node_id, node_name, node_known
    local k

    if #options >= 1 and options[1] == "show" then
        -- print out that thing that we print
        local home, node
        if #options == 1 then
            home, node = getNumberAndNode("1")
        else
            home, node = getNumberAndNode(options[2])
        end

        if node == nil then
            CHAT_SYSTEM:AddMessage("No saved location for location " .. home)
        else
            n_known, n_name = GetFastTravelNodeInfo(node)
            CHAT_SYSTEM:AddMessage(n_name .. " is your current home location.")
        end
        return
    end

    if #options == 2 and options[1] == "search" then
        -- do the search!
        for node_id = 1, GetNumFastTravelNodes() do
            node_known, node_name = GetFastTravelNodeInfo(node_id)
            if node_known then k = "" else k = " (unknown)" end

            if string.find(string.lower(node_name), string.lower(options[2])) then
                CHAT_SYSTEM:AddMessage("#" .. node_id .. ": " .. node_name .. k)
            end
        end
        return
    end

    if #options >= 2 and options[1] == "save" then
        -- actually save the ID in our saved variables thing
        -- options: "save 1 173", "save 173" -- the latter defaults to 1
        local n, h
        if #options == 3 then
            h = tonumber(options[2]) -- which home we're saving to
            n = tonumber(options[3])
        else
            h = 1
            n = tonumber(options[2])
        end

        if not n then
            CHAT_SYSTEM:AddMessage(options[2] .. " is not a valid node ID.")
        elseif h < 1 or h > 5 then
            CHAT_SYSTEM:AddMessage(h .. " is not a valid home location.")
        elseif n < GetNumFastTravelNodes() and n > 0 then
            node_known, node_name = GetFastTravelNodeInfo(n)
            if not node_known then
                CHAT_SYSTEM:AddMessage("WARNING: " .. node_name .. " is an undiscovered location! You won't be able to port there.")
            end
            CHAT_SYSTEM:AddMessage(node_name .. " stored as home port location " .. h .. "!")
            if h == 1 then
                HomePort.savedVariables.home1 = n
            elseif h == 2 then
                HomePort.savedVariables.home2 = n
            elseif h == 3 then
                HomePort.savedVariables.home3 = n
            elseif h == 4 then
                HomePort.savedVariables.home4 = n
            elseif h == 5 then
                HomePort.savedVariables.home5 = n
            else
                -- How did we get here?!
                CHAT_SYSTEM:AddMessage("FATAL: " .. h .. " is not a valid home location.")
            end
        end
        return
    end

    if #options >= 1 and options[1] == "help" then
        CHAT_SYSTEM:AddMessage("To use HOMEPort:")
        CHAT_SYSTEM:AddMessage("/hp -- port to your first saved location")
        CHAT_SYSTEM:AddMessage("/hp 1 -- port to your first saved location")
        CHAT_SYSTEM:AddMessage("/hp 2 -- port to your second saved location")
        CHAT_SYSTEM:AddMessage("/hp 3 -- port to your third saved location")
        CHAT_SYSTEM:AddMessage("/hp 4 -- port to your fourth saved location")
        CHAT_SYSTEM:AddMessage("/hp 5 -- port to your fifth saved location")
        CHAT_SYSTEM:AddMessage("/hp show <num> -- display information about your first home, or specified number")
        CHAT_SYSTEM:AddMessage("/hp save <num> <ID> -- save the Wayshrine ID <ID> as your home")
        CHAT_SYSTEM:AddMessage("/hp search <name> -- returns the Wayshrine IDs of locations matching <name>")
        CHAT_SYSTEM:AddMessage("/hp help -- this message")
        return
    end
end

function HomePort:Initialize ()
    HomePort.savedVariables = ZO_SavedVars:New("HomePort_SavedVariables", HomePort.version, nil, HomePort.default_vars)
end

function HomePort.OnAddOnLoaded (event, name)
    if name == HomePort.name then
        HomePort:Initialize()
    end
end

SLASH_COMMANDS["/hp"] = HomePort.Choose

EVENT_MANAGER:RegisterForEvent(HomePort.name, EVENT_ADD_ON_LOADED, HomePort.OnAddOnLoaded)