# Wrapper class for MaxMindDB
# @see https://github.com/yhirose/maxminddb wrapped library documentation
class Maxmind
  attr_reader :city, :isp

  # Look up the Location data associated with a given IP address.
  # @see MaxMindDB#lookup
  # @param ip_address [String] the IP address to perform a lookup on
  # @return {MaxMindDB::Result} found results
  # @return [nil] no results
  def self.lookup(ip_address)
    @city.lookup(ip_address)
  end

  # Look up the ISP data associated with a given IP address
  # @param (see Maxmind#lookup)
  # @return {MaxMindDB::Result} found results
  # @return [nil] no results
  def self.isp_lookup(ip_address)
    @isp.lookup(ip_address)
  end

  # this does not happen on class load to give more flexibility
  def self.load!
    db_dir = ENV["MAXMIND_DB_DIRECTORY"] || Settings.maxmind.directory

    unless db_dir
      Rails.logger.warn("not loading maxmind database, directory argument was empty")
      return
    end

    city_path = File.join(db_dir, "GeoIP2-City.mmdb")
    isp_path = File.join(db_dir, "GeoIP2-ISP.mmdb")
    @city ||= MaxMindDB.new(city_path)
    @isp ||= MaxMindDB.new(isp_path)
  end

end
