-- Shopkeeper Utility Functions File
-- Last Updated August 10, 2014
-- Written August 2014 by Dan Stone (@khaibit) - dankitymao@gmail.com
-- Released under terms in license accompanying this file.
-- Distribution without license is prohibited!

-- Translate from the i18n table
function Shopkeeper.translate(stringName)
  local result = Shopkeeper.i18n.localized[stringName]
  assert(result, ("The id %q was not found in the current locale"):format(stringName))
  return result
end

function Shopkeeper.localizedNumber(numberValue)
  local stringPrice = numberValue
  -- Insert thousands separators for the price
  -- local stringPrice = numberValue
  local subString = "%1" .. Shopkeeper.translate("thousandsSep") .."%2"
  while true do
    stringPrice, k = string.gsub(stringPrice, "^(-?%d+)(%d%d%d)", subString)
    if (k == 0) then break end
  end

  return stringPrice
end

-- Create a textual representation of a time interval
-- (X and Y) or Z in LUA is the equivalent of C-style
-- ternary syntax X ? Y : Z so long as Y is not false or nil
function Shopkeeper.textTimeSince(theTime, useLowercase)
  local secsSince = GetTimeStamp() - theTime
  if secsSince < 90 then
    return ((useLowercase and zo_strformat(Shopkeeper.translate('timeSecondsAgoLC'), secsSince)) or
             zo_strformat(Shopkeeper.translate('timeSecondsAgo'), secsSince))
  elseif secsSince < 5400 then
    return ((useLowercase and zo_strformat(Shopkeeper.translate('timeMinutesAgoLC'), math.floor(secsSince / 60.0))) or
             zo_strformat(Shopkeeper.translate('timeMinutesAgo'), math.floor(secsSince / 60.0)))
  elseif secsSince < 86400 then
    return ((useLowercase and zo_strformat(Shopkeeper.translate('timeHoursAgoLC'), math.floor(secsSince / 3600.0))) or
             zo_strformat(Shopkeeper.translate('timeHoursAgo'), math.floor(secsSince / 3600.0)))
  else
    return ((useLowercase and zo_strformat(Shopkeeper.translate('timeDaysAgoLC'), math.floor(secsSince / 86400.0))) or
             zo_strformat(Shopkeeper.translate('timeDaysAgo'), math.floor(secsSince / 86400.0)))
  end
end

-- A utility function to grab all the keys of the sound table
-- to populate the options dropdown
function Shopkeeper.soundKeys()
  local keyList = {}
  for i = 1, #Shopkeeper.alertSounds do table.insert(keyList, Shopkeeper.alertSounds[i].name) end
  return keyList
end

-- A utility function to find the key associated with a given value in
-- the sounds table.  Best we can do is a linear search unfortunately,
-- but it's a small table.
function Shopkeeper.searchSounds(sound)
  for i, theSound in ipairs(Shopkeeper.alertSounds) do
    if theSound.sound == sound then return theSound.name end
  end

  -- If we hit this point, we didn't find what we were looking for
  return nil
end

function Shopkeeper.searchSoundNames(name)
  for i,theSound in ipairs(Shopkeeper.alertSounds) do
    if theSound.name == name then return theSound.sound end
  end
end