-- vim:fileencoding=utf-8:foldmethod=marker:foldmarker={{{,}}}

-- {{{ Libraries
local awful = require("awful")
local beautiful = require("beautiful")
local gears = require("gears")
local watch = require("awful.widget.watch")
local wibox = require("wibox")
local naughty = require("naughty")
-- End libraries }}}


-- {{{ Variables
local ramgraph_widget = {}
local popup
-- uses for notify
local ram_last_id

--luacheck:ignore 231
local total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap
-- End variables }}}


-- {{{ Misc functions

local function getPercentage(value)
    return math.floor(value / (total+total_swap) * 100 + 0.5) .. '%'
end

local function getPercent(value, total)
    return math.floor(value / total * 100)
end

-- End misc functions}}}


-- {{{ Worker function
local function worker(user_args)

    -- {{{ Variables
    local args = user_args or {}
    local timeout = args.timeout or 1

    -- {{{ Diagram part
    local color_used = args.color_used or beautiful.bg_urgent
    local color_free = args.color_free or beautiful.fg_normal
    local color_buf  = args.color_buf  or beautiful.border_color_active
    local widget_show_buf = args.widget_show_buf or false
    local widget_height = args.widget_height or 25
    local widget_width = args.widget_width or 25
    -- End diagram part }}}


    -- {{{ Text part

    local font = args.font or 'FontAwesome bold 9'
    local show_percentage = args.show_percentage or true
    local low_load_color = args.low_load_color or '#669900'
    local medium_load_color = args.medium_load_color or '#F5F549'
    local high_load_color = args.high_load_color or '#FF8000'
    local critical_load_color = args.critical_load_color or '#FF0000'
    local medium_load_percent = args.medium_load_percent or 50
    local high_load_percent = args.high_load_percent or 70
    local critical_load_percent = args.critical_load_percent or 85

    -- End text part}}}


    -- End variables }}}


    -- {{{ Widget settings
    --- Main ram widget shown on wibar
    ramgraph_widget = wibox.widget {
        {
            border_width = 0,
            colors = {
               color_used,
               color_free,
               color_buf,
            },
            display_labels = false,
            forced_height = widget_height,
            forced_width = widget_width,
            widget = wibox.widget.piechart,
            id = 'graphw',
        },
        {
            id = 'textw',
            font = font,
            widget = wibox.widget.textbox,
            text = "init text",
        },
        layout = wibox.layout.align.horizontal,

        set_widget_values = function (self, stdout)
            total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap =
                stdout:match('(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*Swap:%s*(%d+)%s*(%d+)%s*(%d+)')

--            local testing_total = string.format("%.1f",(tonumber(total) // tonumber(1024) / tonumber (1024)))
--            local testing_free = string.format("%.1f",tonumber (free) // tonumber(1024) / tonumber (1024))
--            local testing_used = string.format("%.1f", tonumber(used) // tonumber(1024) / tonumber(1024))
--            naughty.notify({text =
--                testing_total .. " total\n"
--                .. testing_free .. " free\n"
--                .. testing_used .. " used\n"
--        })

            local MiB_Total = tostring(tonumber(total) // 1024)
            local MiB_Used = tostring(tonumber(used) // 1024)
            local MiB_Free = tostring((tonumber(MiB_Total) - tonumber(MiB_Used)))
            local Output_free = ""
            local color = ""
            if tonumber(MiB_Free) > 1024 then
                Output_free = string.format("%.1f", tostring(tonumber(MiB_Free) / 1024)) .. " GiB"
            else
                Output_free = MiB_Free .. " MiB"
            end

            local used_percent = getPercent(MiB_Used, MiB_Total)
            if tonumber(used_percent) > critical_load_percent then
                color = critical_load_color
                ram_last_id = naughty.notify ({
                    title = "RAM load is critical",
                    text = "You have too little free RAM. Close some apps to free RAM",
                    preset = naughty.config.presets.critical,
                    replaces_id = ram_last_id,
                    --icon = critical_ram_icon,
                }).id
            elseif tonumber(used_percent) > high_load_percent then
                color = high_load_color
            elseif tonumber(used_percent) > medium_load_percent then
                color = medium_load_color
            else
                color = low_load_color
            end
            if show_percentage then
                local free_percent = getPercent(MiB_Free, MiB_Total)
                Output_free = Output_free .. "/" .. tostring(free_percent) .. "% "
            else 
                Output_free = Output_free .. " "
            end

            if widget_show_buf then
                self:get_children_by_id('graphw')[1].data = { used, free, buff_cache }
            else
                self:get_children_by_id('graphw')[1].data = { used, total-used }
            end
            self:get_children_by_id('textw')[1]:set_markup("<span color='"..color.."'>"..Output_free.."</span>")

            if popup.visible then
               popup:get_widget():get_children_by_id('graphw')[1].data_list = {
                  {'used ' .. getPercentage(used + used_swap), used + used_swap},
                  {'free ' .. getPercentage(free + free_swap), free + free_swap},
                  {'buff_cache ' .. getPercentage(buff_cache), buff_cache}
                }
            end
        end
    }


    --- {{{ popup
    --- Widget which is shown when user clicks on the ram widget
    local popup = awful.popup{
       ontop = true,
       visible = false,
       widget = {
          widget = wibox.widget.piechart,
          forced_height = 200,
          forced_width = 400,
          colors = {
             color_used,
             color_free,
             color_buf,  -- buf_cache
          },
       },
       shape = gears.shape.rounded_rect,
       border_color = beautiful.border_color_active,
       border_width = 1,
       offset = { y = 5 },
    }
    -- End popup }}}


    -- End widget settings }}}


    local update_widget = function (widget, stdout, _, _, _)
        widget:set_widget_values(stdout)
    end


    -- {{{ watch
    watch('bash -c "LANGUAGE=en_US.UTF-8 free | grep -z Mem.*Swap.*"', timeout, update_widget, ramgraph_widget
    )
    -- End watch}}}


    -- {{{ Widget buttons
    ramgraph_widget:buttons(
        awful.util.table.join(
           awful.button({}, 1, function()
                 popup:get_widget().data_list = {
                    {'used ' .. getPercentage(used + used_swap), used + used_swap},
                    {'free ' .. getPercentage(free + free_swap), free + free_swap},
                    {'buff_cache ' .. getPercentage(buff_cache), buff_cache}
                }

                if popup.visible then
                   popup.visible = not popup.visible
                else
                   popup:move_next_to(mouse.current_widget_geometry)
                end
            end)
        )
    )
    -- End widget buttons }}}


    return ramgraph_widget
end
-- End worker function }}}


return setmetatable(ramgraph_widget, { __call = function(_, ...)
    return worker(...)
end })
