#include "pch.h"

#include "legacy_canvas_view_services.h"

#include "app.h"
#include "legacy_preference_storage.h"
#include "node_canvas.h"

namespace pp::panopainter {
namespace {

class LegacyCanvasViewServices final : public pp::app::CanvasViewServices {
public:
    explicit LegacyCanvasViewServices(App& app) noexcept
        : app_(app)
    {
    }

    void reset_camera(const pp::app::CanvasCameraState& state) override
    {
        if (!app_.canvas || !app_.canvas->m_canvas) {
            return;
        }

        app_.canvas->m_canvas->m_cam_rot = glm::mat4(
            state.rotation[0], state.rotation[1], state.rotation[2], state.rotation[3],
            state.rotation[4], state.rotation[5], state.rotation[6], state.rotation[7],
            state.rotation[8], state.rotation[9], state.rotation[10], state.rotation[11],
            state.rotation[12], state.rotation[13], state.rotation[14], state.rotation[15]);
        app_.canvas->m_canvas->m_cam_pos = {
            state.position[0],
            state.position[1],
            state.position[2],
        };
        app_.canvas->m_canvas->m_cam_fov = state.field_of_view_degrees;
        app_.canvas->m_canvas->m_pan = {
            state.pan[0],
            state.pan[1],
        };
    }

    void set_density(const pp::app::CanvasViewDensityPlan& plan) override
    {
        if (!app_.canvas) {
            return;
        }

        app_.canvas->set_density(plan.density);
        save_legacy_canvas_viewport_density(plan.density);
    }

    void set_cursor_mode(const pp::app::CanvasViewCursorModePlan& plan) override
    {
        if (!app_.canvas) {
            return;
        }

        const auto mode = static_cast<int>(plan.mode);
        app_.canvas->set_cursor_visibility(static_cast<NodeCanvas::kCursorVisibility>(mode));
        save_legacy_canvas_cursor_mode(mode);
    }

private:
    App& app_;
};

} // namespace

pp::foundation::Status execute_legacy_canvas_camera_reset(App& app)
{
    LegacyCanvasViewServices services(app);
    return pp::app::execute_canvas_camera_reset(services);
}

pp::foundation::Status execute_legacy_canvas_view_density(App& app, float density)
{
    LegacyCanvasViewServices services(app);
    return pp::app::execute_canvas_view_density(density, services);
}

pp::foundation::Status execute_legacy_canvas_cursor_mode(App& app, int mode)
{
    LegacyCanvasViewServices services(app);
    return pp::app::execute_canvas_view_cursor_mode(mode, services);
}

} // namespace pp::panopainter
