/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef DEF_VIEWPORT
#define DEF_VIEWPORT

#include "Structs/Box.hpp"
#include "Structs/Vector.hpp"
#include <cstdint>

class Viewport
{
    public:
        Viewport() : Viewport(Box(0.f, 0.f, 1.f, 1.f)) {}
        explicit Viewport(const Box &view) : Viewport(view, view) {}

        Viewport(const Box &source, const Box &target) :
        m_source(source), m_target(target)
        {
            updateRatio();
        }

        /// Projects \p point from source to target coordinates
        Vector project(const Vector &point) const
        {
            return Vector(
                (point.x - m_source.left) * m_widthRatio + m_target.left,
                (point.y - m_source.top) * m_heightRatio + m_target.top);
        }

        /// Projects \p x , \p y from source to target coordinates
        Vector project(std::int32_t x, std::int32_t y) const
        {
            return project(Vector(static_cast<float>(x),
                                  static_cast<float>(y)));
        }

        void setSource(const Box &source)
        {
            m_source = source;
            updateRatio();
        }

        const Box &getSource() const
        {
            return m_source;
        }

        const Box &getTarget() const
        {
            return m_target;
        }

        Vector getTargetSize() const
        {
            return Vector(m_target.width, m_target.height);
        }

    private:
        void updateRatio()
        {
            m_widthRatio = m_source.width > 0.f ?
                m_target.width / m_source.width : 1.f;

            m_heightRatio = m_source.height > 0.f ?
                m_target.height / m_source.height : 1.f;
        }

        Box m_source, m_target;
        float m_widthRatio, m_heightRatio;
};

#endif
