-- Offers window tiling functionnality

local awful = require("awful")

-- Placements
local leftTileGeometry = awful.placement.scale
    + awful.placement.left
    + awful.placement['maximize_vertically']
local rightTileGeometry = awful.placement.scale
    + awful.placement.right
    + awful.placement['maximize_vertically']
local maximizedTileGeometry = awful.placement.scale
    + awful.placement['maximize']


-- Check if geometries are the same
local geometryEquals = function(geo1, geo2)
    return geo1.width == geo2.width and geo1.height == geo2.height and 
        geo1.x == geo2.x and geo1.y == geo2.y
end

-- Try to apply a tile placement to a client
-- return false if it changed nothing
local applyTile = function(c, geometry)
    local initialGeometry = {
        x = c.x,
        y = c.y,
        width = c.width,
        height = c.height
    }
    local newGeometry = geometry(c, {honor_workarea=true, to_percent = 0.5})
    return not geometryEquals(initialGeometry, newGeometry)
end

local screenLeft = function(geo)
    return function (c)
        local newScreen = c.screen.get_next_in_direction(c.screen, "left")
        if newScreen ~= nil then
            c.screen = newScreen
            applyTile(c, geo)
        end
    end
end

local screenRight = function(geo)
    return function (c)
        local newScreen = c.screen.get_next_in_direction(c.screen, "right")
        if newScreen ~= nil then
            c.screen = newScreen
            applyTile(c, geo)
        end
    end
end

return {
    key = {
        tileRight = function (c)
            c.maximized = true
            if not applyTile(c, rightTileGeometry) then
                screenRight(leftTileGeometry)(c)
            end
        end,
        tileLeft = function (c)
            c.maximized = true
            if not applyTile(c, leftTileGeometry) then
                screenLeft(rightTileGeometry)(c)
            end
        end,
        screenLeft = screenLeft(maximizedTileGeometry),
        screenRight = screenRight(maximizedTileGeometry),
        toggleMaximized = function (c)
            if not c.maximized then
                c.maximized = true
            else
                if not applyTile(c, maximizedTileGeometry) then 
                    c.maximized = false
                end
            end
        end,
        minimize = function(c) 
            c.minimized = true
        end
    }
}