-- Copyright (C) 2010 Tyson Brown
-- 
-- This file is part QuestHelper2, an AddOn for World of Warcraft.
-- 
-- QuestHelper2 is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- 
-- QuestHelper2 is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
-- 
-- You should have received a copy of the GNU General Public License
-- along with QuestHelper2. If not, see <http://www.gnu.org/licenses/>.

if LibDebug then LibDebug() end
local shared = select(2, ...)

-- A small cache for unitSeen
local recently_seen_map, recently_seen_list = {}, {}

-- Returns true if the unit has been seen recently, or doesn't exist.
-- If this function returns false, the unit is remembered and subsequenct
-- calls will return true.
-- The purpose of this function is to collect information about a unit
-- the first time it is seen, and then ignore it subsequently.
function shared.unitSeen(unit)
  local guid = UnitGUID(unit or "target")
  
  if not guid or recently_seen_map[guid] then
    return true
  end
  
  if #recently_seen_list > 50 then
    -- Remove the item at the end of the list.
    recently_seen_map[table.remove(recently_seen_list)] = nil
  end
  
  table.insert(recently_seen_list, guid)
  recently_seen_map[guid] = true
  
  return false
end

local function parseUnitGUID(unit)
  local guid = UnitGUID(unit or "target")
  
  if guid then
    return tonumber(string.sub(guid, -14, -14), 16)%8,
           tonumber(string.sub(guid, -12, -9), 16)
  end
end

--[[
-- Why? Because somebody is smoking crack.
local vehicle_npcs = {
  [41910] = true, -- Humphrey Digsong
  [42466] = true, -- Terrath the Steady
  [46750] = true, -- Fusion Core
  [40825] = true, -- Erunak Stonespeaker
}
]]

function shared.npcID(unit)
  local unit_type, id = parseUnitGUID(unit)
  if unit_type == 3 or -- 5 is for vehicles, but some npcs are apparently vehicles.
     unit_type == 5 then
    return id
  end
end

function shared.objectID(unit)
  local unit_type, id = parseUnitGUID(unit)
  if unit_type == 1 then return id end
end
