#include "fesa/math/vector.hpp"

#include <gtest/gtest.h>

#include <cmath>
#include <stdexcept>
#include <utility>

namespace fesa {
namespace {

TEST(DenseMath, VectorOwnsAndChecksContiguousStorage) {
    Vector empty{0};
    EXPECT_EQ(empty.size(), 0U);
    EXPECT_DOUBLE_EQ(empty.norm(), 0.0);
    EXPECT_NO_THROW(empty.scale(3.0));
    EXPECT_NO_THROW(empty.axpy(-2.0, Vector{0}));
    EXPECT_THROW(static_cast<void>(empty[0]), std::out_of_range);

    Vector original{3};
    original[0] = 1.0;
    original[1] = -2.0;
    original[2] = 3.0;

    EXPECT_EQ(original.data() + 1, &original[1]);
    EXPECT_EQ(original.data() + 2, &original[2]);
    const Vector& constOriginal = original;
    EXPECT_EQ(constOriginal.data() + 2, &constOriginal[2]);

    Vector copied{original};
    EXPECT_NE(copied.data(), original.data());
    copied[0] = 99.0;
    EXPECT_DOUBLE_EQ(original[0], 1.0);

    Vector copyAssigned{0};
    copyAssigned = original;
    EXPECT_NE(copyAssigned.data(), original.data());
    copyAssigned[1] = 17.0;
    EXPECT_DOUBLE_EQ(original[1], -2.0);

    Vector moved{std::move(copied)};
    EXPECT_EQ(copied.size(), 0U);
    EXPECT_EQ(moved.size(), 3U);
    EXPECT_DOUBLE_EQ(moved[0], 99.0);
    EXPECT_NO_THROW(copied.scale(4.0));

    Vector moveAssigned{1, -1.0};
    moveAssigned = std::move(copyAssigned);
    EXPECT_EQ(copyAssigned.size(), 0U);
    EXPECT_EQ(moveAssigned.size(), 3U);
    EXPECT_DOUBLE_EQ(moveAssigned[1], 17.0);

    Vector rhs{3};
    rhs[0] = 4.0;
    rhs[1] = 5.0;
    rhs[2] = -6.0;
    EXPECT_DOUBLE_EQ(original.dot(rhs), -24.0);
    EXPECT_NEAR(original.norm(), std::sqrt(14.0), 1.0e-15);

    Vector scaled{original};
    scaled.scale(-0.5);
    EXPECT_DOUBLE_EQ(scaled[0], -0.5);
    EXPECT_DOUBLE_EQ(scaled[1], 1.0);
    EXPECT_DOUBLE_EQ(scaled[2], -1.5);

    Vector accumulated{3};
    accumulated[0] = 1.0;
    accumulated[1] = 2.0;
    accumulated[2] = 3.0;
    Vector increment{3};
    increment[0] = 4.0;
    increment[1] = -1.0;
    increment[2] = 0.5;
    accumulated.axpy(2.0, increment);
    EXPECT_DOUBLE_EQ(accumulated[0], 9.0);
    EXPECT_DOUBLE_EQ(accumulated[1], 0.0);
    EXPECT_DOUBLE_EQ(accumulated[2], 4.0);

    EXPECT_THROW(static_cast<void>(original[3]), std::out_of_range);
    EXPECT_THROW(static_cast<void>(constOriginal[3]), std::out_of_range);
    EXPECT_THROW(static_cast<void>(original.dot(Vector{2})), std::invalid_argument);
    EXPECT_THROW(original.axpy(1.0, Vector{2}), std::invalid_argument);
}

} // namespace
} // namespace fesa
