--   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/>. 
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local awmtk2 = require("awmtk2")
local simplepam_status,simplepam = pcall(require,"simplepam")
local dkjson = require("dkjson")

if not simplepam_status then
    return function() end
end
local readable = gears.filesystem.file_readable
if not G_KeyboardLock then
    G_KeyboardLock = awful.keygrabber {
        mask_modkeys = true,
        mask_event_callback = true
    }
end
local reset_textbox_timer

local function _preload(args)
    local widget_root
    local widget_bar
    local widget
    do -- {{{ Lock bar
        local config_path = root_path.."/themes/"..global.theme.."/config/lockbar.json"
        if readable(config_path) then
            local style = awmtk2.create_style("lockbar", awmtk2.default, args.style)
            local templates = awmtk2.create_template_lib("lockbar",awmtk2.templates,args.templates)
            local t = awmtk2.build_templates(templates,style)
            local config_file = io.open(config_path,"r")
            local config = config_file:read("*a")
            config_file:close()
            widget_bar = wibox.widget(t.container(t.wibar(builder(
                config,
                {
                    screen = args.screen,
                    style = style.wibar
                }
            )),{
                forced_width = args.screen.geometry.width,
                forced_height = style.wibar.height
            }))
        end
    end -- }}}
    do -- {{{ Lock widget
        local style = awmtk2.create_style("lockpanel", awmtk2.default, args.style)
        local templates = awmtk2.create_template_lib("lockpanel",awmtk2.templates,args.templates)
        local t = awmtk2.build_templates(templates,style)
        local config_path = root_path.."/themes/"..global.theme.."/config/lockpanel.json"
        local lockpanel 
        if readable(config_path) then
            local config_file = io.open(config_path,"r")
            local config = config_file:read("*a")
            config_file:close()
            local layout = {
                layout = wibox.layout.fixed.vertical,
                spacing = style.base.spacing
            }
            lockpanel = t.container({
                layout,
                widget = wibox.container.place,
                valign = "center",
                halign = "center"
            },{
                bgimage = style.base.panel_bgimage,
                bg = style.base.panel_bg,
                forced_height = style.base.panel_height,
                forced_width = style.base.panel_width
            })
            for k,v in pairs(dkjson.decode(config)) do
                table.insert(layout,{
                    require(k)(v),
                    widget = wibox.container.place,
                    valign = "center",
                    halign = "center"
                })
            end
        end
        widget = wibox.widget({
            {
                t.container({
                    {
                        (readable(os.getenv("HOME").."./.face") and t.center(t.container({
                            widget = wibox.widget.imagebox,
                            resize = true,
                            image = "./.face",
                        }),{
                            height = style.base.icon_height,
                            width = style.base.icon_width
                        })),
                        t.container(t.textbox({
                            markup = "Logged in as "..os.getenv("USER")
                        })),
                        t.container(t.textbox({
                            markup = "Enter password",
                            id = "pinentry"
                        }),{
                            id = "pin_container"
                        }),
                        layout = wibox.layout.fixed.vertical,
                        spacing = style.base.spacing
                    },
                    widget = wibox.container.place,
                    valign = "center",
                    halign = "center"
                },{
                    bgimage = style.base.panel_bgimage,
                    bg = style.base.panel_bg,
                    forced_height = style.base.panel_height,
                    forced_width = style.base.panel_width
                }),
                lockpanel,
                layout = wibox.layout.fixed.horizontal,
                spacing = style.base.spacing
            },
            widget = wibox.container.place,
            valign = "center",
            halign = "center"
        })
        local pinentry = widget:get_children_by_id("pinentry")[1]
        local pinentry_container = widget:get_children_by_id("pin_container")[1]
        pinentry_container:connect_signal("button::press",function()
            if (not awful.keygrabber.current_instance) then return end
            G_KeyboardLock:stop()
            awful.prompt.run {
                prompt = "Password: ",
                history_max = 0,
                history_path = "/dev/null",
                exe_callback = function(input,textbox)
                    G_KeyboardLock:start()
                    if simplepam(input) then
                        pinentry:set_markup("Enter password")
                        awesome.emit_signal("unlock_screen")
                    else
                        pinentry:set_markup("Enter password")
                    end
                end,
                highlighter = ((not args.show) and function(b,a)
                    return b:gsub(".","*"),a:gsub(".","*")
                end),
                textbox = pinentry,
                done_callback = function()
                    if (args.screen.lock.visible) and (not awful.keygrabber.current_instance) then
                        G_KeyboardLock:start()
                    end
                end
            }
        end)
    end -- }}}
    do -- {{{ Lock screen root
        local style = awmtk2.create_style("lockscreen", awmtk2.default, args.style)
        local templates = awmtk2.create_template_lib("lockscreen",awmtk2.templates,args.templates)
        local t = awmtk2.build_templates(templates,style)
        local wallpaper 
        if readable(root_path.."/wallpaper.txt") then
            wallpaper_f = io.open(root_path.."/wallpaper.txt","r")
            wallpaper = wallpaper_f:read("*a")
            wallpaper_f:close()
        end
        widget_root = awful.popup(t.popup({
            {
                widget_bar,
                widget,
                layout = wibox.layout.stack,
            },
            widget = wibox.container.background,
            forced_width = args.screen.geometry.width,
            forced_height = args.screen.geometry.height,
            bgimage = function(cont,cr,width,height)
                local s = gears.surface.load_uncached_silently(
                    wallpaper or 
                    beautiful.wallpaper
                )
                local bg_width,bg_height = gears.surface.get_size(s)
                local scale = height/bg_height
                if width/bg_width > scale then
                    scale = width/bg_width
                end
                cr:translate((width - (bg_width*scale))/2,(height - (bg_height*scale))/2)
                cr:rectangle(0,0, (bg_width*scale), (bg_height*scale))
                cr:clip()
                cr:scale(scale,scale)
                cr:set_source_surface(s)
                cr:paint()
            end
        }))
    end -- }}}
    print(widget_root,"test")
    return widget_root
end

return function(args)
    awesome.connect_signal("lock_screen",function()
        if (not awful.keygrabber.current_instance) then
            G_KeyboardLock:start()
            print("Keygrabber started")
        end
    end)
    awesome.connect_signal("unlock_screen",function()
        if (awful.keygrabber.current_instance == G_KeyboardLock) then
            G_KeyboardLock:stop()
        end
    end)
    for s in screen do 
        s.lock = _preload(gears.table.join(args,{
            screen = s
        }))
        awesome.connect_signal("lock_screen",function()
            s.lock.visible = true
        end)
        awesome.connect_signal("unlock_screen",function()
            s.lock.visible = false
        end)
    end
end
