#include <gtest/gtest.h>
#include <selectorParse.h>
#include <stdexcept>

namespace lcamera_dev {
namespace {

TEST(TrimWhitespaceTest, StripsLeadingAndTrailingWhitespace)
{
	EXPECT_EQ(trimWhitespace("  foo bar  "), "foo bar");
	EXPECT_EQ(trimWhitespace("\t\nvalue\r\n"), "value");
	EXPECT_EQ(trimWhitespace("no-trim"), "no-trim");
	EXPECT_EQ(trimWhitespace(""), "");
}

TEST(ParseDeviceSelectorTest, BareOpaqueIdIsLibcameraId)
{
	const std::vector<SelectorCriterion> criteria =
		parseDeviceSelector("/base/soc/i2c@1/imx219@10");

	ASSERT_EQ(criteria.size(), 1u);
	EXPECT_EQ(criteria[0].kind, SelectorCriterionKind::LibcameraId);
	EXPECT_EQ(criteria[0].value, "/base/soc/i2c@1/imx219@10");
}

TEST(ParseDeviceSelectorTest, ExplicitLcameraIdPrefix)
{
	const std::vector<SelectorCriterion> criteria =
		parseDeviceSelector("lcamera-id:foo bar baz");

	ASSERT_EQ(criteria.size(), 1u);
	EXPECT_EQ(criteria[0].kind, SelectorCriterionKind::LibcameraId);
	EXPECT_EQ(criteria[0].value, "foo bar baz");
}

TEST(ParseDeviceSelectorTest, ParsesTypedPrefixes)
{
	const std::vector<SelectorCriterion> criteria =
		parseDeviceSelector(
			"index:0;model:imx219;model-substr:Logi;location:external");

	ASSERT_EQ(criteria.size(), 4u);
	EXPECT_EQ(criteria[0].kind, SelectorCriterionKind::Index);
	EXPECT_EQ(criteria[0].value, "0");
	EXPECT_EQ(criteria[1].kind, SelectorCriterionKind::Model);
	EXPECT_EQ(criteria[1].value, "imx219");
	EXPECT_EQ(criteria[2].kind, SelectorCriterionKind::ModelSubstr);
	EXPECT_EQ(criteria[2].value, "Logi");
	EXPECT_EQ(criteria[3].kind, SelectorCriterionKind::Location);
	EXPECT_EQ(criteria[3].value, "external");
}

TEST(ParseDeviceSelectorTest, EscapedSemicolonInValue)
{
	const std::vector<SelectorCriterion> criteria =
		parseDeviceSelector("lcamera-id:foo\\;bar;model:aaaa");

	ASSERT_EQ(criteria.size(), 2u);
	EXPECT_EQ(criteria[0].kind, SelectorCriterionKind::LibcameraId);
	EXPECT_EQ(criteria[0].value, "foo;bar");
	EXPECT_EQ(criteria[1].kind, SelectorCriterionKind::Model);
	EXPECT_EQ(criteria[1].value, "aaaa");
}

TEST(ParseDeviceSelectorTest, EmptySelectorThrows)
{
	EXPECT_THROW(parseDeviceSelector(""), std::runtime_error);
	EXPECT_THROW(parseDeviceSelector("   "), std::runtime_error);
}

TEST(ParseDeviceSelectorTest, UnknownPrefixThrows)
{
	EXPECT_THROW(
		parseDeviceSelector("serial:abc"),
		std::runtime_error);
}

TEST(ParseDeviceSelectorTest, EmptyClauseThrows)
{
	EXPECT_THROW(
		parseDeviceSelector("model:imx219;;location:front"),
		std::runtime_error);
}

TEST(ParseDeviceSelectorTest, EmptyValueThrows)
{
	EXPECT_THROW(
		parseDeviceSelector("model:"),
		std::runtime_error);
}

} // namespace
} // namespace lcamera_dev
