local awful = require("awful")
local gears = require("gears")
local wibox = require("wibox")

local function start_moving(widget)
    local mouse_coords = mouse.coords()
    local offset_x = widget.x - mouse_coords.x
    local offset_y = widget.y - mouse_coords.y
    if not mousegrabber.isrunning() then
        mousegrabber.run(function(coords)
            widget.x = coords.x + offset_x 
            widget.y = coords.y + offset_y
            return coords.buttons[3]
        end,"plus")
    end
end

return function(args)
    local args = args or {}
    local container_settings = {
        screen = s,
        bg = "#00000000",
        visible = true,
        type = "desktop",
        height = args.height or 64,
        width = args.width or 64,
        x = args.x or 40,
        y = args.y or 40
    }
    
    local widget = wibox.widget {
        {
            image = args.image,
            resize = true,
            widget = wibox.widget.imagebox,
            id = "imagebox"
        },
        widget = wibox.widget.background,
        layout = wibox.layout.fixed.vertical
    }
    container = wibox(container_settings)
    widget:get_children_by_id("imagebox")[1]:connect_signal("button::press",
        function(self,x,y,button) 
            if button == 1 then
                awful.spawn(args.command)
            elseif button == 3 then
                start_moving(container)
            elseif button == 4 then
                container.height = container.height / 0.9
                container.width = container.width / 0.9
            elseif button == 5 then
                container.height = container.height * 0.9
                container.width = container.width * 0.9
            end
        end)
    widget:get_children_by_id("imagebox")[1]:connect_signal("button::release",
        function()
            if mousegrabber.isrunning() then
                mousegrabber.stop()
            end
            args.x = container.x
            args.y = container.y
            args.width = container.width
            args.height = container.height
        end)
    container:set_widget(widget)
    return container
end
