local naughty  = require("naughty")
local wibox    = require("wibox")
local json     = require("dkjson")
local https    = require("ssl.https")
local gears    = require("gears")

local function factory(args)
  local args = args or {}
  local timeout     = args.timeout or 120
  local calluri     = args.uri or "https://masa.dy.fi/api/games/stats/minecraft/?type=server_status"
  local minecraft   = { widget = wibox.widget.textbox() }
  local settings    = args.settings or function() end
  local hideempty   = args.hideempty or false  
  local hideoffline = args.hideoffline or true  
  minecraft.widget:set_markup("N/A")

  function minecraft.show(tout)
    minecraft.hide()
  
    minecraft.notification = naughty.notify({
      text = minecraft.notification_text,
      -- icon = minecraft.icon
      timeout = 0
    })
  end

  function minecraft.hide()
    if minecraft.notification then
      naughty.destroy(minecraft.notification)
    end
  end

  function minecraft.attach(obj)
    obj:connect_signal("mouse::enter", function()
      minecraft.show()
    end)
    
    obj:connect_signal("mouse::leave", function()
      minecraft.hide()
    end)
  end

  function minecraft.update()
    local response, error = https.request(calluri)
    local obj, pos, err = json.decode (response, 1, nil)

    totalplayers = 0
    if not err then
      local text = "Status" .. "\t" .. "Version" .. "\t" .. "#" .. "\t" .. "Server" .. "\t" .. "\n"
      for k, v in pairs(obj) do
        if (tonumber(v.num_players) > 0 or not hideempty) and (v.status == "online" or not hideoffline) then
          text = text .. v.status .. "\t"
          text = text .. v.version .. "\t"
          text = text .. v.num_players .. "\t"
          text = text .. v.server_name .. "\t"
          text = text .. "\n"

          if v.players then
            for i, p in pairs(v.players) do
              text = text .. '\t\t' .. p .. '\n'
            end
          end
        end

        local n = tonumber(v.num_players)
        totalplayers = totalplayers + n
      end
      minecraft.notification_text = text
      minecraft.totalplayers = totalplayers;
      -- minecraft.widget:set_markup("N/A")
      widget = minecraft.widget
      settings()
    end
  end

  minecraft.attach(minecraft.widget)
  
  gears.timer {
    timeout   = timeout,
    autostart = true,
    callback  = minecraft.update
  }

  return minecraft
end

return factory
