/*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_SCALED_PIXEL
#define DEF_SCALED_PIXEL

#include <cmath>
#include <type_traits>

/// View-size relative unit of length
/// The scaled pixel is defined such that 1sp = 1px on a
/// reference view width of 1280px (by default)
class ScaledPixel
{
    public:
        explicit ScaledPixel(float viewWidth) :
        m_viewWidth(viewWidth), m_referenceWidth(1280.f) {}

        explicit ScaledPixel(float viewWidth, float referenceWidth) :
        m_viewWidth(viewWidth), m_referenceWidth(referenceWidth) {}

        /// Returns the actual pixel size of \p scaledPixel,
        /// projected on \p viewWidth
        template <typename T> T operator() (T scaledPixel) const
        {
            static_assert(std::is_arithmetic<T>::value, "T must be arithmetic");
            return static_cast<T>(m_viewWidth *
                static_cast<float>(scaledPixel) / m_referenceWidth);
        }

        /// Specialization for float, floors by default
        float operator () (float scaledPixel, bool rounded = true) const
        {
            return rounded ? floorf(operator()<float>(scaledPixel))
                           : operator()<float>(scaledPixel);
        }

        /// Projects \p scaledPixel to actual pixel size,
        /// if lower than \p upperBound
        float lower(float scaledPixel, float upperBound) const
        {
            const float projected = operator()(scaledPixel, false);
            return projected < upperBound ? projected : upperBound;
        }

    private:
        float m_viewWidth;
        const float m_referenceWidth;
};

#endif
