#include <psemek/test/test.hpp>

#include <psemek/util/ndarray.hpp>

using namespace psemek::util;

test_case(util_ndarray_empty)
{
	ndarray<int, 1> a;
	expect_equal(a.size(), 0);
	expect(a.empty());

	ndarray<int, 2> b;
	expect_equal(b.size(), 0);
	expect(b.empty());

	ndarray<int, 3> c;
	expect_equal(c.size(), 0);
	expect(c.empty());
}

test_case(util_ndarray_size)
{
	ndarray<int, 1> a({16});
	expect(!a.empty());
	expect_equal(a.size(), 16);
	expect_equal(a.width(), 16);

	ndarray<int, 2> b({8, 16});
	expect(!b.empty());
	expect_equal(b.size(), 8 * 16);
	expect_equal(b.width(), 8);
	expect_equal(b.height(), 16);

	ndarray<int, 3> c({4, 8, 16});
	expect(!c.empty());
	expect_equal(c.size(), 4 * 8 * 16);
	expect_equal(c.width(), 4);
	expect_equal(c.height(), 8);
	expect_equal(c.depth(), 16);
}

test_case(util_ndarray_init)
{
	ndarray<int, 2> a({16, 16}, 42);
	for (std::size_t i = 0; i < a.width(); ++i)
		for (std::size_t j = 0; j < a.height(); ++j)
			expect_equal(a(i, j), 42);
}

test_case(util_ndarray_release)
{
	std::unique_ptr<int[]> p(new int[256]);
	auto q = p.get();

	ndarray<int, 2> a({16, 16}, std::move(p));
	expect_equal(a.size(), 256);
	expect_equal(a.width(), 16);
	expect_equal(a.height(), 16);
	expect_equal_ptr(a.data(), q);

	p = a.release();
	expect_equal(a.size(), 0);
	expect(a.empty());
	expect_equal_ptr(a.data(), nullptr);
	expect_equal_ptr(p.get(), q);
}

test_case(util_ndarray_move)
{
	ndarray<int, 2> a({16, 16}, 42);

	auto p = a.data();

	ndarray<int, 2> b(std::move(a));
	expect(a.empty());
	expect_equal(a.size(), 0);
	expect(!b.empty());
	expect_equal(b.size(), 256);
	expect_equal_ptr(b.data(), p);

	ndarray<int, 2> c;
	c = std::move(b);
	expect(b.empty());
	expect_equal(b.size(), 0);
	expect(!c.empty());
	expect_equal(c.size(), 256);
	expect_equal_ptr(c.data(), p);
}

test_case(util_ndarray_copy)
{
	ndarray<int, 2> a({16, 16}, 42);

	ndarray<int, 2> b(a.copy());
	expect(!a.empty());
	expect(!b.empty());
	expect_equal(a.size(), b.size());
	expect_equal(a.size(), 256);
	expect_different_ptr(a.data(), b.data());
}

test_case(util_ndarray_lifetime)
{
	std::weak_ptr<int> p;

	{
		ndarray<std::shared_ptr<int>, 2> a({16, 16}, std::make_shared<int>(42));
		p = a(0, 0);
		for (std::size_t i = 0; i < a.width(); ++i)
		{
			for (std::size_t j = 0; j < a.height(); ++j)
			{
				expect(a(i, j));
				expect_equal(*a(i, j), 42);
				expect_equal(a(i, j).use_count(), a.size());
			}
		}
	}

	expect(!p.lock());
	expect_equal(p.use_count(), 0);
}
