local awful = require("awful")
local beautiful = require("beautiful")
local gears = require("gears")
local mouse_utils = require("utils.mouse")

-- Focus clients under mouse
client.connect_signal("mouse::enter", function(c)
    c:emit_signal("request::activate", "mouse_enter", {raise = false})
end)


client.connect_signal("manage", function (c)
    -- Set the window as a slave (put it at the end of others instead of setting it as master)
    if not awesome.startup then
        awful.client.setslave(c)
    end

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

    -- Unminimize and unmaximize the other clients
    for _, o in ipairs(client.get()) do
        o.minimized = false
        o.maximized = false
        o.fullscreen = false
    end

    gears.timer.delayed_call(function()
        local geometry = c:geometry()
        local x = geometry.x + geometry.width/2
        local y = geometry.y + geometry.height/2
        mouse.coords({x = x, y = y}, true)
    end)
end)

-- Reload config when screen geometry changes
screen.connect_signal("property::geometry", awesome.restart)


-- ===================================================================
-- Garbage collection (allows for lower memory consumption)
-- ===================================================================

collectgarbage("setpause", 110)
collectgarbage("setstepmul", 1000)

client.connect_signal("property::maximized", function(focused)
    local hide = focused.maximized or focused.fullscreen
    for _, c in ipairs(client.get()) do
        if not c.floating and c.screen == focused.screen and c.first_tag == focused.first_tag then
            c.minimized = hide
        end
    end

    focused.minimized = false
end)

client.connect_signal("unmanage", function(unmanaged)
    if unmanaged.maximized then
        for _, c in ipairs(client.get()) do
            if not c.floating and c.screen == unmanaged.screen then
                c.minimized = false
            end
        end
    end
end)

client.connect_signal("focus", function(c)
    if #c.screen.clients > 1 then
        c.border_color = beautiful.border_focus
    end
    gears.timer.delayed_call(mouse_utils.move_mouse_onto_focused_client)
end)

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