/*
 * Copyright (c) 1999-2021 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 PW_CORE_AABB_HPP
#define PW_CORE_AABB_HPP

#include "vector.hpp"
#include <cstddef>
#include <numeric>
#include <pw/core/vector.hpp>

#include <algorithm>
#include <vector>

namespace pw {

template <typename Scalar, std::size_t N> struct aabb final {

    using value_type = vector<Scalar, N>;

    value_type min{};
    value_type max{};

    constexpr auto dimension() const noexcept { return max - min; }

    static constexpr auto make(
        const std::vector<pw::vector<Scalar, N>>& vertices) -> aabb<Scalar, N> {
        return std::accumulate(
            std::begin(vertices), std::end(vertices),
            aabb{.min{vertices.front()}, .max{vertices.front()}},
            [](const auto& prev, const auto& e) {
            return aabb{.min{e.min(prev.min)}, .max{e.max(prev.max)}};
        });
    }

    static constexpr auto make_from_indexed_vertices(
        const std::vector<pw::vector<Scalar, N>>& vertices,
        std::vector<size_t>& indices) -> aabb<Scalar, N> {
        return std::accumulate(std::begin(indices), std::end(indices),
                               aabb{.min{vertices[indices.front()]},
                                    .max{vertices[indices.front()]}},
                               [&vertices](const auto& prev, const auto& e) {
            return aabb{.min{vertices[e].min(prev.min)},
                        .max{vertices[e].max(prev.max)}};
        });
    }
};

} // namespace pw

#endif
