--   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/>.

-- library for constructing bindable keys
local asckey = {
    keymap = {}
}
local awful = require("awful")
local gears = require("gears")

asckey.set_keymap = function(keymap)
    for k,v in pairs(keymap) do
        asckey.keymap[v] = k
    end
end

asckey.get_keycomb = function(name)
    local modifiers = {}
    name = name:gsub("[^%s%+]+%+",function(v)
        if v == "modkey+" then v = global.modkey.."+" end
        table.insert(modifiers,v:sub(1,-2))
        return ""
    end)
    return modifiers,name
end

asckey.k = function(name,callback,description)
    if not asckey.keymap[name] then
        return {}
    end
    local modifiers,key = asckey.get_keycomb(asckey.keymap[name])
    return awful.key(modifiers,key,
        callback,
    description)
end

asckey.custom_binds = function()
    local custom_keys = {}
    for comm,_ in pairs(asckey.keymap) do
        if not comm:match("^:.*") then
            table.insert(custom_keys,asckey.k(comm,function()
                awful.spawn(comm)
            end,{description = comm, group = "custom"}))
        end
    end
    return custom_keys
end

asckey.context = function(keys)
    local context = {keys = keys, key_lookup = {},active = false}
    for _,v in pairs(keys) do
        context.key_lookup[v] = true
    end
    function context:activate()
        context.active = true
        root.keys(gears.table.join(
            root.keys(),
            self.keys
        ))
    end
    function context:deactivate()
        context.active = false
        local root_keys = root.keys()
        for i = #root_keys,1,-1 do
            if self.key_lookup[root_keys[i]] then
                table.remove(root_keys,i)
            end
        end
        root.keys(root_keys)
    end 
    return context
end

return asckey
