local beautiful = require("beautiful")
local awful = require("awful")
require "functions"

-- Signal function to execute when a new client appears.
client.connect_signal(
    "manage",
    function(c)
        -- Set the windows at the slave
        if not awesome.startup then awful.client.setslave(c) end

        -- Prevent clients from being unreachable after screen count changes.
        if awesome.startup and not c.size_hints.user_position and not c.size_hints.program_position then
            awful.placement.no_offscreen(c)
        end

        update_titlebars(c)

        if not c.below then
            c:raise()
        end
    end
)

-- Enable sloppy focus, so that focus follows mouse.
client.connect_signal(
    "mouse::enter",
    function(c)
        c:emit_signal("request::activate", "mouse_enter", {raise = false})
    end
)

client.connect_signal(
    "focus",
    function(c)
        c.border_color = beautiful.border_focus
    end
)

client.connect_signal(
    "unfocus",
    function(c)
        c.border_color = beautiful.border_normal
    end
)

-- Disable PiP Snapping
client.connect_signal(
    "property::struts",
    function(c)
        if c:struts().left ~= 0 or c:struts().right ~= 0 or c:struts().top ~= 0 or c:struts().bottom ~= 0 then
            c:struts({ left = 0, right = 0, top = 0, bottom = 0 })
        end
    end
)

client.connect_signal(
    "property::floating",
    function(c)
        if c.floating and not c.maximized and not c.fullscreen then
            c.placement = awful.placement.centered
        end

        update_titlebars(c)
    end
)

client.connect_signal(
    "property::maximized",
    update_titlebars
)

client.connect_signal(
    "property::fullscreen",
    update_titlebars
)

-- Automatically unminimize windows
client.connect_signal(
    "property::minimized",
    function(c)
        if c.minimized then
            c.minimized = false
        end
    end
)

-- Re-set wallpaper when a screen's geometry changes (e.g. different resolution)
screen.connect_signal("property::geometry", set_wallpaper)

tag.connect_signal(
    "property::selected",
    function (t)
        local selected = tostring(t.selected) == "false"
        if selected then
            local focus_timer = timer({ timeout = 0.05 })
            focus_timer:connect_signal(
                "timeout",
                function()
                local c = awful.mouse.client_under_pointer()
                if c ~= nil and not c.below then
                    client.focus = c
                    c:raise()
                end
                focus_timer:stop()
            end)
            focus_timer:start()
        end
    end
)

tag.connect_signal(
    "property::layout",
    function (t)
        for _, c in pairs(t.clients(t)) do
            update_titlebars(c)
        end
    end
)