/*
 * Copyright 2023 Hartmut Seichter
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#ifndef PARADISO_AABB_HPP
#define PARADISO_AABB_HPP

#include <paradiso/globals.hpp>
#include <paradiso/vector.hpp>

namespace paradiso {
struct AABB final {

    Vector2<float> top_left{};
    Vector2<float> bottom_right{};

    static constexpr AABB from_vertices(const auto& vertices) noexcept {

        Matrix<2, 2, float> min_max;
        min_max.set_slice<2, 1>(0, 0) = vertices.front();
        min_max.set_slice<2, 1>(1, 0) = vertices.front();

        for (const auto& v : vertices) {
            min_max(0, 0) = std::min(min_max(0, 0), v.x());
            min_max(0, 1) = std::min(min_max(0, 1), v.y());
            min_max(1, 0) = std::min(min_max(1, 0), v.x());
            min_max(1, 1) = std::min(min_max(1, 1), v.y());
        }

        return {.top_left = Vector2<float>::make(min_max(0, 0), min_max(0, 1)),
                .bottom_right =
                    Vector2<float>::make(min_max(1, 0), min_max(1, 1))};
    }

    bool constexpr is_inside(const Vector2<float>& v) const {
        return (v.x() >= top_left.x() && v.x() <= bottom_right.x() &&
                v.y() >= top_left.y() && v.y() <= bottom_right.y());
    }
};

} // namespace paradiso

#endif