#include "Device/Mask/Polygon.h"

#include "Base/Axis/Bin.h"
#include "Tests/GTestWrapper/google_test.h"
#include <memory>

const std::vector<std::pair<double, double>> points1 = {
    {4.0, 2.0}, {-4.0, 2.0}, {-4.0, -2.0}, {4.0, -2.0}, {4.0, 2.0}};


TEST(Polygon, SimpleRectangle)
{
    // simple closed rectangle
    Polygon polygon(points1);
    EXPECT_DOUBLE_EQ(32.0, polygon.area());
    EXPECT_TRUE(polygon.contains(0.0, 0.0));
    EXPECT_TRUE(polygon.contains(4.0, 2.0));
    EXPECT_TRUE(polygon.contains(-4.0, -2.0));
    EXPECT_TRUE(polygon.contains(-4.0, -2.0));
    EXPECT_FALSE(polygon.contains(0.0, 2.01));
    EXPECT_FALSE(polygon.contains(4.0, -2.01));

    // unclosed rectangle (should be closed automatically)
    Polygon polygon2({{4., 2.}, {-4., 2.}, {-4., -2.}, {4., -2.}});
    EXPECT_DOUBLE_EQ(32.0, polygon2.area());
    EXPECT_TRUE(polygon2.contains(0.0, 0.0));
    EXPECT_TRUE(polygon2.contains(4.0, 2.0));
    EXPECT_TRUE(polygon2.contains(-4.0, -2.0));
    EXPECT_TRUE(polygon2.contains(-4.0, -2.0));
    EXPECT_FALSE(polygon2.contains(0.0, 2.01));
    EXPECT_FALSE(polygon2.contains(4.0, -2.01));
}

//     *******
//      *   *
//       * *
//        *
//       * *
//      *   *
//     *******

TEST(Polygon, SandWatchShape)
{
    Polygon polygon({{2., 2.}, {-2., 2.}, {2., -2.}, {-2., -2.}, {2., 2.}});
    //    std::cout << polygon << std::endl;

    // for some reason area calculation doesn't work for boost's polygon of such shape
    // EXPECT_DOUBLE_EQ(8.0, polygon.area());

    EXPECT_TRUE(polygon.contains(2.0, 2.0));
    EXPECT_TRUE(polygon.contains(-2.0, 2.0));
    EXPECT_TRUE(polygon.contains(0.0, 0.0));
    EXPECT_TRUE(polygon.contains(0.0, 1.0));

    EXPECT_FALSE(polygon.contains(1.0, 0.0));
    EXPECT_FALSE(polygon.contains(-1.5, 0.5));
}

TEST(Polygon, ContainsBin)
{
    // simple closed rectangle
    Polygon polygon(points1);

    Bin1D binx1 = Bin1D::FromTo(3.5, 4.5);
    Bin1D biny1 = Bin1D::FromTo(1.5, 2.5);
    EXPECT_TRUE(polygon.contains(binx1, biny1));

    Bin1D binx2 = Bin1D::FromTo(-5, -3.9);
    Bin1D biny2 = Bin1D::FromTo(-3, 2.6);
    EXPECT_TRUE(polygon.contains(binx2, biny2));
}

TEST(Polygon, Clone)
{
    Polygon polygon(points1);

    std::unique_ptr<Polygon> clone(polygon.clone());
    EXPECT_DOUBLE_EQ(32.0, clone->area());
    EXPECT_TRUE(clone->contains(0.0, 0.0));
    EXPECT_TRUE(clone->contains(4.0, 2.0));
    EXPECT_TRUE(clone->contains(-4.0, -2.0));
    EXPECT_TRUE(clone->contains(-4.0, -2.0));
    EXPECT_FALSE(clone->contains(0.0, 2.01));
    EXPECT_FALSE(clone->contains(4.0, -2.01));
}
