#include "core.hpp"
#include <glm/trigonometric.hpp>
#include <pch.hpp>

#include <scene/scene_camera.hpp>
#include <glm/ext/matrix_clip_space.hpp>

namespace OpenEngine {
    SceneCamera::SceneCamera()
    {
        RecalculateProjection();
    }

    void SceneCamera::SetOrthographic(float size, float near_clip, float far_clip)
    {
        projection_type = ProjectionType::Orthographic;
        orthographic_size = size;
        orthographic_near = near_clip;
        orthographic_far = far_clip;

        RecalculateProjection();
    }

    void SceneCamera::SetPerspective(float fov_value, float near_clip, float far_clip)
    {
        projection_type = ProjectionType::Perspective;
        fov = fov_value;
        perspective_near = near_clip;
        perspective_far = far_clip;

        RecalculateProjection();
    }

    void SceneCamera::SetViewportSize(uint32_t width, uint32_t height)
    {
        OE_CORE_ASSERT(width > 0 && height > 0, "Viewport size invalid.");
        aspect_ratio = (float)width / (float)height;

        RecalculateProjection();
    }

    void SceneCamera::RecalculateProjection()
    {

        if (projection_type == ProjectionType::Orthographic) {
            float ortho_left = -orthographic_size * aspect_ratio * 0.5;
            float ortho_right = orthographic_size * aspect_ratio * 0.5;
            float ortho_bottom = orthographic_size * -0.5;
            float ortho_top = orthographic_size * 0.5;

            projection = glm::ortho(
                    ortho_left, ortho_right,
                    ortho_bottom, ortho_top,
                    orthographic_near, orthographic_far);
        }
        else if (projection_type == ProjectionType::Perspective) {
            projection = glm::perspective(
                    glm::radians(fov), aspect_ratio,
                    perspective_near, perspective_far);
        }
    }
}
