local naughty    = require("naughty")
local wibox      = require("wibox")
local json       = require("lanxu/dkjson")
local gears      = require("gears")
local focused    = require("awful.screen").focused
local easy_async = require("awful.spawn").easy_async

local function factory(args)
  local args = args or {}
  local calluri     = args.uri or "https://api.ipify.org"
  local settings    = args.settings or function() end
  local homeaddress = args.homeaddress or nil

  local ip = { widget = wibox.widget.textbox() }
  ip.widget:set_markup("N/A")

  function ip.attach(obj)
    obj:connect_signal("button::press", function()
      ip.update()
    end)
  end

  function ip.update()
    local cmd = string.format("curl -s " .. "'" .. calluri .. "'")
    
    address = "N/A"
    settings()

    easy_async(cmd, function(response, stderr, reason, exit_code)
      address = response
      address = string.gsub(address, "[^0-9.]", "")
      if address == homeaddress then
        address = "Home"
      end

      ip.address = address
      widget = ip.widget

      settings()
    end)
  end

  ip.attach(ip.widget)

  address = "N/A"
  settings()

  ip.update()

  return ip
end

return factory
