--[[----------------------------------------------------------------------------

Copyright (c) 2010, Timothy Armes (http:--www.timothyarmes.com)

All rights reserved.

------------------------------------------------------------------------------]]

Hierarchy = {}

Hierarchy.hierarchy = {}
Hierarchy.lrKeyword_KeywordMaster = nil

local numKeywords

local function cacheKeywords(pt, lrKeywords, parent, parentString)

   if not parentString then parentString = "" end
   
   for k, v in pairs(lrKeywords) do
   
      local name = v:getName()
      local lcName = LrStringUtils.lower(name)
      local keywordInfo = {
         parent = parent,
         menuString = name .. parentString,
         keyword = v,
         origName = name
      }
      
      if name == "Keyword Master" and parent == nil then
         Hierarchy.lrKeyword_KeywordMaster = v
      end
      
      if Hierarchy.hierarchy[lcName] then
         table.insert(Hierarchy.hierarchy[lcName], keywordInfo)
      else
         Hierarchy.hierarchy[lcName] = { keywordInfo }
      end

      numKeywords = numKeywords + 1
      if numKeywords % 10 == 0 then pt.numKeywords = numKeywords end
      
      -- Cache the hierarchy
      
      local children = v:getChildren()
      if children then cacheKeywords(pt, children, v, " > " .. v:getName() .. parentString) end
      
   end

end

function Hierarchy.cacheHierarchy(pt)

      numKeywords = 0
      cacheKeywords(pt, LrApplication.activeCatalog():getKeywords(), nil)
      pt.cachedHierarchy = true
      
end