local dkjson = require("dkjson")
local handler = io.open(global.config_dir.."stickers.json","r")
local stickers = {} 
local objects = {}
if handler then
    stickers = dkjson.decode(handler:read("*a") or "[]") or {}
end
local image = require("widgets.stickers.image")
return function(s)
    objects.image = objects.image or {}
    for id, args in pairs(stickers.image or {}) do
        s["sticker_image"..tostring(args.id)] = image(args)
        objects[args.type][args.id] = s["sticker_image"..tostring(args.id)]
    end
    awesome.connect_signal("stickers::add",function(x,y,h,w,cmd,t,arg)
        if t == "image" then
            stickers.image = stickers.image or {}
            objects.image = objects.image or {}
            local args = {
                x = x,
                y = y,
                height = h,
                width = w,
                command = cmd,
                image = arg,
                type = "image",
                id = #stickers.image+1
            }
            table.insert(stickers.image,args)
            s["sticker_image"..tostring(#stickers.image)] = image(args)
            objects.image[#stickers.image] = s["sticker_image"..tostring(#stickers.image)]
        end
    end)
    awesome.connect_signal("stickers::remove",function(type,id) 
        if stickes[type] and stickers[type][id] then
            stickers[type][id] = nil
            objects[type][id] = nil
        end
        s["sticker_"..tostring(type)..tostring(id)] = nil
    end)
    awesome.connect_signal("stickers::save",function()
        for type, obj_list in pairs(objects) do
            for id, obj in pairs(obj_list) do
                stickers[type][id].x = obj.x
                stickers[type][id].y = obj.y
                stickers[type][id].width = obj.width
                stickers[type][id].height = obj.height
            end
        end
        local handler = io.open(global.config_dir.."stickers.json","w")
        handler:write(dkjson.encode(stickers) or "")
        handler:close()
    end)
end
