-- This is just a helper camera harcoded system to navigate the tree, but there isn't
-- anything interesting here and in fact is better if you go away from this module xD

local camera = { 
    x = love.graphics.getWidth() / 2, 
    y = love.graphics.getHeight() / 2, 
    scale = 1,
    transform = love.math.newTransform()
}

local drag = { active = false, startX = 0, startY = 0, initX = 0, initY = 0 }

local function update_camera_transform()
    camera.transform:reset()
    
    local w, h = love.graphics.getDimensions()
    local cx, cy = w/2, h/2
    
    camera.transform:translate(cx, cy)
    camera.transform:scale(camera.scale)
    camera.transform:translate(-camera.x, -camera.y)
end

function camera.reset()
    camera.x = love.graphics.getWidth() / 2
    camera.y = love.graphics.getHeight() / 2
    camera.scale = 1
    update_camera_transform()
end

function camera.update(dt)
    local speed = 200 * dt / camera.scale
    if love.keyboard.isDown("w") then camera.y = camera.y - speed end
    if love.keyboard.isDown("s") then camera.y = camera.y + speed end
    if love.keyboard.isDown("a") then camera.x = camera.x - speed end
    if love.keyboard.isDown("d") then camera.x = camera.x + speed end
    if love.keyboard.isDown("e") then camera.scale = camera.scale * (1 + dt) end
    if love.keyboard.isDown("q") then camera.scale = camera.scale / (1 + dt) end

    update_camera_transform()
end

function camera.wheel_moved(x, y)
    camera.scale = camera.scale * (1 + y * 0.1)
    update_camera_transform()
end

function camera.push()
    love.graphics.push()
    love.graphics.replaceTransform(camera.transform)
end

function camera.pop()
    love.graphics.pop()
end

function camera.mousepressed(x, y, button)
    if button == 1 then
        drag.active = true
        drag.startX, drag.startY = x, y
        drag.initX, drag.initY = camera.x, camera.y
    end
end

function camera.mousereleased(x, y, button)
    if button == 1 then
        drag.active = false
    end
end

function camera.mousemoved(x, y, dx, dy)
    if drag.active then
        camera.x = drag.initX - (x - drag.startX) / camera.scale
        camera.y = drag.initY - (y - drag.startY) / camera.scale
        update_camera_transform()
    end
end

return camera