#include "MoveGesture.hpp"

#include "../../../../desktop/state/FocusState.hpp"
#include "../../../../desktop/view/Window.hpp"
#include "../../../../render/Renderer.hpp"
#include "../../../../layout/LayoutManager.hpp"

void CMoveTrackpadGesture::begin(const ITrackpadGesture::STrackpadGestureBegin& e) {
    ITrackpadGesture::begin(e);

    m_window    = Desktop::focusState()->window();
    m_lastDelta = {};
}

void CMoveTrackpadGesture::update(const ITrackpadGesture::STrackpadGestureUpdate& e) {
    if (!m_window)
        return;

    const auto DELTA = e.swipe ? e.swipe->delta : e.pinch->delta;

    if (m_window->m_isFloating) {
        g_layoutManager->moveTarget(DELTA, m_window->layoutTarget());
        m_window->finishAnimation();
        return;
    }

    // tiled window -> displace, then execute a move dispatcher on end.

    g_pHyprRenderer->damageWindow(m_window.lock());

    // funny name but works on tiled too lmao
    m_lastDelta += DELTA;
    m_window->m_floatingOffset = (m_lastDelta * 0.5F).clamp(Vector2D{-100.F, -100.F}, Vector2D{100.F, 100.F});

    g_pHyprRenderer->damageWindow(m_window.lock());
}

void CMoveTrackpadGesture::end(const ITrackpadGesture::STrackpadGestureEnd& e) {

    if (!m_window)
        return;

    if (m_window->m_isFloating || m_lastDelta.size() < 0.1F)
        return;

    // tiled: attempt to move window in the given direction

    const auto WINDOWPOS = m_window->position(Desktop::View::IGeometric::GEOMETRIC_GOAL) + m_window->m_floatingOffset;

    m_window->m_floatingOffset = {};

    if (std::abs(m_lastDelta.x) > std::abs(m_lastDelta.y)) {
        // horizontal
        g_layoutManager->moveInDirection(m_window->layoutTarget(), m_lastDelta.x > 0 ? "r" : "l");
    } else {
        // vertical
        g_layoutManager->moveInDirection(m_window->layoutTarget(), m_lastDelta.y > 0 ? "b" : "t");
    }

    const auto GOAL = m_window->position(Desktop::View::IGeometric::GEOMETRIC_GOAL);

    m_window->positionAnimation()->setValueAndWarp(WINDOWPOS);
    m_window->move(GOAL);

    m_window.reset();
}
