local gputemp = require("gputemp")
local dpmsstatus = require("dpmsstatus")
local lain = require("lain")
local vicious = require("vicious") -- Custom
local beautiful = require("beautiful") -- CPU temp
local wibox = require("wibox")

-- Variables
local valuecolor = "white"

-- Helpers
function file_exists(name)
  local f = io.open(name,"r")
  if f ~= nil then io.close(f) return true else return false end
end

function create_markup(key, value, postfix, color)
    return key .. " <span foreground='" .. color .. "'><b>" .. value .. postfix .."</b></span>"
end

-- Spacer
spacer = wibox.widget.textbox()
--spacer.text = "-"
spacer.forced_width = 8;

-- CPU
mycpu = lain.widget.cpu({
  settings = function()
    widget.markup = create_markup("CPU", cpu_now.usage, " %", valuecolor)
  end
})

-- MEM
mymem  = lain.widget.mem({
  settings = function()
    widget.markup = create_markup("MEM", mem_now.used, " MB", valuecolor)
  end
})

-- GPU
mygputemp = wibox.widget.textbox()
vicious.register(mygputemp, gputemp, create_markup("GPU", "$0", "℃", valuecolor), 15, "AMD")

-- Volume
volume = lain.widget.pulseaudio({
  scallback = function()
    return "pacmd list-sinks | grep -Paoz \"(?s)(\\* index.*$(pactl info | grep -e 'ink' | cut -d' ' -f3).*(index)?)\" | tr -d '\\000' | grep -e 'index' -e 'device.string' -e 'name:' -e 'volume: front' -e 'muted'"
  end,
  settings = function()
    volstr = volume_now.left .. " "
    volcolor = valuecolor
    if volume_now.muted == "yes" then
      volcolor = "red"
    end
    widget.markup = create_markup("VOL", volstr, "%", volcolor)
  end
})

-- Text clock
mytextclock = wibox.widget.textclock(create_markup("Date","%Y-%m-%d %H:%M","", valuecolor))

lain.widget.calendar({
  followtag = true,
  attach_to = {mytextclock}
})

-- CPU temperature
local tempfile = "/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A03:00/device:14/ATK0110:00/hwmon/hwmon1/temp1_input"
if file_exists(tempfile) == false then
  tempfile = "/sys/class/thermal/thermal_zone0/temp"
end

mycputemp = lain.widget.temp({
  tempfile = tempfile, 
  settings = function()
    widget.markup = create_markup("CPU", coretemp_now, "℃", valuecolor)
  end
})

-- Weather Widget
myweather = lain.widget.weather({
  city_id = 634963,
  lang = "fi",
  followtag = true,
  settings = function()
    widget.markup = create_markup("Tampere", weather_now.main.temp, "℃", valuecolor)
  end
});

-- DPMS
mydpmsstatus = wibox.widget.textbox()
vicious.register(mydpmsstatus, dpmsstatus, function(widget, args)
  color = valuecolor
  if args[0] == "Enabled" then
    return create_markup("DPMS", "ON", "", color)
  else
    color = "red"
    return create_markup("DPMS", "OFF", "", color)
  end
end)

-- Servers
local mcstatus = require("lanxu/mcstatus")
myserverstatus = mcstatus({
  settings = function()
    widget.markup = create_markup("PLAYERS", totalplayers, "", valuecolor)
  end
})

