--   This file is part of Reno desktop.
--
--  Reno desktop is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
--
--  Reno desktop is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
--
--  You should have received a copy of the GNU General Public License along with Reno desktop. If not, see <https://www.gnu.org/licenses/>. 
-- Quick application launcher
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local awmtk2 = require("awmtk2")
local beautiful = require("beautiful")
local menubar_utils = require("menubar").utils

local function synchronous_ls(dir)
    local filenames = {}
    local handler = io.popen("ls -1 "..dir,"r")
    handler:read("*a"):gsub("[^\n]+",function(filename)
        table.insert(filenames,filename)
    end)
    return filenames
end

return function(args)
    local style = awmtk2.create_style("launcher", 
        awmtk2.generic.button_list, args.style)
    local templates = awmtk2.create_template_lib("launcher", awmtk2.templates, args.templates)
    local t = awmtk2.build_templates(templates,style)
    local w = wibox.widget({
        layout = ((args.vertical and
            wibox.layout.fixed.vertical) or
            wibox.layout.fixed.horizontal
        ),
        spacing = style.base.spacing
    })
    local path = args.path or root_path.."/links"
    if gears.filesystem.dir_readable(path) then
        local files = synchronous_ls(path)
        for k,v in pairs(files) do
            local data = menubar_utils.parse_desktop_file(path.."/"..v)
            local new_widget = wibox.widget(t.button({
                image = menubar_utils.lookup_icon_uncached(data.Icon),
                widget = wibox.widget.imagebox,
            }))
            local exec = data.Exec:gsub("%%%w","")
            new_widget:connect_signal("button::press",style.button.onpress)
            new_widget:connect_signal("button::release",style.button.onrelease)
            new_widget:connect_signal("button::press",function()
                awful.spawn(exec)
            end)
            w:add(new_widget)
        end
    end
    return w
end
