--   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/>. 
-- Wallpaper list widget
local awful = require("awful")
local pager = require("pager")
local beautiful = require("beautiful")
local gears = require("gears")
local wibox = require("wibox")
local awmtk2 = require("awmtk2")
local thumbnailer = require("thumbnail")

local function ls(path)
    local ls_data = io.popen("find "..path.." -maxdepth 1 -type f \\( -name \\*.jpg -o -name \\*.png \\) -exec realpath {} \\;")
    local output = {}
    if ls_data then
        ls_data:read("*a"):gsub("[^\n]+",function(capt)
            table.insert(output,capt)
        end)
        ls_data:close()
        return output
    end
    error("Failed to process directory "..path)
end

return function(args)
    local style = awmtk2.create_style("wallpapers",
        awmtk2.generic.iconified_widget,args.style)
    local templates = awmtk2.create_template_lib("wallpapers",awmtk2.templates,args.templates)
    local t = awmtk2.build_templates(templates,style)
    -- set wallpaper
    local fhandler = io.open(root_path.."/wallpaper.txt","r")
    if fhandler then
        local wallpaper_path = fhandler:read("*a")
        gears.wallpaper.maximized(wallpaper_path,args.screen)
    else
        -- try to set wallpaper from theme settings
        if beautiful.wallpaper then
            gears.wallpaper.maximized(beautiful.wallpaper,args.screen)
        end
    end
    -- update wallpaper preference and set wallpaper
    local function set_wallpaper(s)
        local handler = io.open(root_path.."/wallpaper.txt","w")
        handler:write(s)
        handler:close()
        gears.wallpaper.maximized(s,args.screen)
    end
    if not args.path then
        args.path = os.getenv("HOME")..".local/share/wallpapers/"
    end
    args.path = args.path:gsub("$HOME",os.getenv("HOME"))
    -- read wallpapers from wallpaper directory
    local image_list = ls(args.path)
    -- generate thumbnails to save memory
    thumbnailer.generate(args.path,args.path.."/.thumbnails",60)
    -- create a layout for wallpaper buttons
    local layout = wibox.widget({
        layout = wibox.layout.grid,
        forced_num_cols = args.columns or 4,
        homogenous = true,
        expand = true,
        orientation = "vertical",
        spacing = style.base.spacing
    }) 
    -- create layout popup
    local popup = awful.popup(t.popup({
        t.container(layout),
        t.textbox({
            markup = "Page 0/0",
            id = "page_index"
        }),
        layout = wibox.layout.fixed.vertical
    },{
        visible = false
    }))
    local page_index = popup.widget:get_children_by_id("page_index")[1]
    -- set up a pager for having multiple pages of wallpapers
    local pager_size = ((args.rows and args.columns) and args.rows*args.columns) or 20
    local pager = pager(layout,{},pager_size)
    -- add wallpaper buttons
    for k,v in pairs(image_list) do
        local new_button = wibox.widget(t.button(t.center({
            image = args.path.."/.thumbnails/"..v:match("/[^/]*$"),
            resize = true,
            widget = wibox.widget.imagebox
        },{
            height = args.height or 60,
            width = args.width or 100
        })))
        new_button:connect_signal("button::press",style.button.onpress)
        new_button:connect_signal("button::release",style.button.onrelease)
        new_button:connect_signal("button::press",function(self,x,y,button)
            if button == 1 then
                set_wallpaper(v)
            elseif button == 4 then
                pager:prev()
                page_index:set_markup("Page "..tostring(pager.index+1).."/"..
                    tostring(math.ceil(#image_list/pager_size)))
            elseif button == 5 then
                pager:next()
                page_index:set_markup("Page "..tostring(pager.index+1).."/"..
                    tostring(math.ceil(#image_list/pager_size)))
            end
        end)
        table.insert(pager.list,new_button)
    end
    page_index:set_markup("Page "..tostring(pager.index+1).."/"..
        tostring(math.ceil(#image_list/pager_size)))
    -- update pager
    pager:update()
    -- make popup togglable
    popup:connect_signal("button::press",function(self,x,y,button)
        if button == 3 then
            popup.visible = false
        end
    end)
    -- create popup button
    local clip_widget = wibox.widget(t.button({
        image = beautiful.wallpapers_icon,
        resize = true,
        widget = wibox.widget.imagebox
    }))
    clip_widget:connect_signal("button::press",style.button.onpress)
    clip_widget:connect_signal("button::release",style.button.onrelease)
    clip_widget:connect_signal("button::press",function(self,x,y,button)
        if button == 1 then
            popup.visible = (not popup.visible)
            if popup.visible then
                popup:move_next_to(mouse.current_widget_geometry)
            end
        end
    end)
    return clip_widget
end
