// Copyright 2020 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

#include <algorithm>

#include "pw_bytes/array.h"
#include "pw_protobuf/encoder.h"
#include "pw_protobuf/wire_format.h"
#include "pw_span/span.h"
#include "pw_stream/memory_stream.h"
#include "pw_unit_test/framework.h"

// These header files contain the code generated by the pw_protobuf plugin.
// They are re-generated every time the tests are built and are used by the
// tests to ensure that the interface remains consistent.
//
// The purpose of the tests in this file is primarily to verify that the
// generated C++ interface is valid rather than the correctness of the
// low-level encoder.
#include "pw_protobuf_test_protos/full_test.pwpb.h"
#include "pw_protobuf_test_protos/importer.pwpb.h"
#include "pw_protobuf_test_protos/non_pw_package.pwpb.h"
#include "pw_protobuf_test_protos/proto2.pwpb.h"
#include "pw_protobuf_test_protos/repeated.pwpb.h"

#define EXPECT_SEQ_EQ(seq1, seq2) \
  EXPECT_TRUE(std::equal(seq1.begin(), seq1.end(), seq2.begin(), seq2.end()))

namespace pw::protobuf {
namespace {

using test::pwpb::Bool;
using test::pwpb::Enum;

namespace Bar = test::pwpb::Bar;
namespace BaseMessage = test::pwpb::BaseMessage;
namespace ConstrainedRepeatedTest = test::pwpb::ConstrainedRepeatedTest;
namespace Crate = test::pwpb::Crate;
namespace DeviceInfo = test::pwpb::DeviceInfo;
namespace Foo = test::pwpb::Foo;
namespace IntegerMetadata = test::pwpb::IntegerMetadata;
namespace KeyValuePair = test::pwpb::KeyValuePair;
namespace Overlay = test::pwpb::Overlay;
namespace Period = test::pwpb::Period;
namespace Pigweed = test::pwpb::Pigweed;
namespace Proto = test::pwpb::Proto;
namespace RepeatedTest = test::pwpb::RepeatedTest;

namespace imported {
namespace Timestamp = ::pw::protobuf::test::imported::pwpb::Timestamp;
}  // namespace imported

template <uint32_t val>
constexpr std::byte ToByte() {
  static_assert(val <= 0xff);
  return static_cast<std::byte>(val);
}

template <typename T, typename Container>
constexpr bool Contains(Container haystack, const T& needle) {
  return std::find(haystack.begin(), haystack.end(), needle) != haystack.end();
}

TEST(Codegen, Codegen) {
  // The encoded size constants don't account for variable length values, so
  // add some additional space for the expected sizes of values we intend to
  // encode.
  constexpr size_t kPigweedMaxValuesSize = 64;
  constexpr size_t kDeviceInfoMaxValuesSize = 32;

  std::byte encode_buffer[Pigweed::kMaxEncodedSizeBytesWithoutValues +
                          kPigweedMaxValuesSize +
                          DeviceInfo::kMaxEncodedSizeBytesWithoutValues +
                          kDeviceInfoMaxValuesSize];
  std::byte temp_buffer[Pigweed::kScratchBufferSizeBytes +
                        kPigweedMaxValuesSize +
                        DeviceInfo::kMaxEncodedSizeBytesWithoutValues +
                        kDeviceInfoMaxValuesSize];
  stream::MemoryWriter writer(encode_buffer);

  Pigweed::StreamEncoder pigweed(writer, temp_buffer);
  ASSERT_EQ(OkStatus(), pigweed.WriteMagicNumber(73));
  ASSERT_EQ(OkStatus(), pigweed.WriteZiggy(-111));
  ASSERT_EQ(OkStatus(), pigweed.WriteErrorMessage("not a typewriter"));
  ASSERT_EQ(OkStatus(), pigweed.WriteBin(Pigweed::Protobuf::Binary::ZERO));
  ASSERT_EQ(OkStatus(), pigweed.WriteData(2, [](stream::Writer& data_writer) {
    PW_TRY(data_writer.Write(std::byte('a')));
    return data_writer.Write(std::byte{'z'});
  }));

  {
    Pigweed::Pigweed::StreamEncoder pigweed_pigweed =
        pigweed.GetPigweedEncoder();
    ASSERT_EQ(OkStatus(), pigweed_pigweed.WriteStatus(Bool::FILE_NOT_FOUND));

    ASSERT_EQ(pigweed_pigweed.status(), OkStatus());
  }

  {
    Proto::StreamEncoder proto = pigweed.GetProtoEncoder();
    ASSERT_EQ(OkStatus(), proto.WriteBin(Proto::Binary::OFF));
    ASSERT_EQ(OkStatus(),
              proto.WritePigweedPigweedBin(Pigweed::Pigweed::Binary::ZERO));
    ASSERT_EQ(OkStatus(),
              proto.WritePigweedProtobufBin(Pigweed::Protobuf::Binary::ZERO));

    PW_TEST_ASSERT_OK(proto.WriteMetaMessage([](auto& meta) {
      PW_TRY(meta.WriteFileName("/etc/passwd"));
      PW_TRY(meta.WriteStatus(Pigweed::Protobuf::Compiler::Status::FUBAR));
      return OkStatus();
    }));

    {
      Pigweed::StreamEncoder nested_pigweed = proto.GetPigweedEncoder();
      ASSERT_EQ(OkStatus(),
                nested_pigweed.WriteErrorMessage("here we go again"));
      ASSERT_EQ(OkStatus(), nested_pigweed.WriteMagicNumber(616));

      {
        DeviceInfo::StreamEncoder device_info =
            nested_pigweed.GetDeviceInfoEncoder();

        {
          KeyValuePair::StreamEncoder attributes =
              device_info.GetAttributesEncoder();
          ASSERT_EQ(OkStatus(), attributes.WriteKey("version"));
          ASSERT_EQ(OkStatus(), attributes.WriteValue("5.3.1"));
        }

        // Exercise flexible capture
        std::string_view key = "chip";
        std::string_view value = "left-soc";

        PW_TEST_ASSERT_OK(
            device_info.WriteAttributesMessage([&](auto& attributes) {
              PW_TRY(attributes.WriteKey(key));
              PW_TRY(attributes.WriteValue(value));
              return OkStatus();
            }));

        ASSERT_EQ(OkStatus(),
                  device_info.WriteStatus(DeviceInfo::DeviceStatus::PANIC));
      }
    }
  }

  for (unsigned i = 0; i < 5; ++i) {
    Proto::ID::StreamEncoder id = pigweed.GetIdEncoder();
    ASSERT_EQ(OkStatus(), id.WriteId(5 * i * i + 3 * i + 49));
  }

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // pigweed.magic_number
    0x08, 0x49,
    // pigweed.ziggy
    0x10, 0xdd, 0x01,
    // pigweed.error_message
    0x2a, 0x10, 'n', 'o', 't', ' ', 'a', ' ',
    't', 'y', 'p', 'e', 'w', 'r', 'i', 't', 'e', 'r',
    // pigweed.bin
    0x40, 0x01,
    // pigweed.data
    0x5a, 0x02, 'a', 'z',
    // pigweed.pigweed
    0x3a, 0x02,
    // pigweed.pigweed.status
    0x08, 0x02,
    // pigweed.proto
    0x4a, 0x56,
    // pigweed.proto.bin
    0x10, 0x00,
    // pigweed.proto.pigweed_pigweed_bin
    0x18, 0x00,
    // pigweed.proto.pigweed_protobuf_bin
    0x20, 0x01,
    // pigweed.proto.meta
    0x2a, 0x0f,
    // pigweed.proto.meta.file_name
    0x0a, 0x0b, '/', 'e', 't', 'c', '/', 'p', 'a', 's', 's', 'w', 'd',
    // pigweed.proto.meta.status
    0x10, 0x02,
    // pigweed.proto.nested_pigweed
    0x0a, 0x3d,
    // pigweed.proto.nested_pigweed.error_message
    0x2a, 0x10, 'h', 'e', 'r', 'e', ' ', 'w', 'e', ' ',
    'g', 'o', ' ', 'a', 'g', 'a', 'i', 'n',
    // pigweed.proto.nested_pigweed.magic_number
    0x08, 0xe8, 0x04,
    // pigweed.proto.nested_pigweed.device_info
    0x32, 0x26,
    // pigweed.proto.nested_pigweed.device_info.attributes[0]
    0x22, 0x10,
    // pigweed.proto.nested_pigweed.device_info.attributes[0].key
    0x0a, 0x07, 'v', 'e', 'r', 's', 'i', 'o', 'n',
    // pigweed.proto.nested_pigweed.device_info.attributes[0].value
    0x12, 0x05, '5', '.', '3', '.', '1',
    // pigweed.proto.nested_pigweed.device_info.attributes[1]
    0x22, 0x10,
    // pigweed.proto.nested_pigweed.device_info.attributes[1].key
    0x0a, 0x04, 'c', 'h', 'i', 'p',
    // pigweed.proto.nested_pigweed.device_info.attributes[1].value
    0x12, 0x08, 'l', 'e', 'f', 't', '-', 's', 'o', 'c',
    // pigweed.proto.nested_pigweed.device_info.status
    0x18, 0x03,
    // pigweed.id[0]
    0x52, 0x02,
    // pigweed.id[0].id
    0x08, 0x31,
    // pigweed.id[1]
    0x52, 0x02,
    // pigweed.id[1].id
    0x08, 0x39,
    // pigweed.id[2]
    0x52, 0x02,
    // pigweed.id[2].id
    0x08, 0x4b,
    // pigweed.id[3]
    0x52, 0x02,
    // pigweed.id[3].id
    0x08, 0x67,
    // pigweed.id[4]
    0x52, 0x03,
    // pigweed.id[4].id
    0x08, 0x8d, 0x01
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(pigweed.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(Codegen, RecursiveSubmessage) {
  // 12 here represents the longest name. Note that all field structure is taken
  // care of, we just have to multiply by how many crates we're encoding, ie. 4.
  std::byte encode_buffer[(Crate::kMaxEncodedSizeBytesWithoutValues + 12) * 4];

  Crate::MemoryEncoder biggest_crate(encode_buffer);
  ASSERT_EQ(OkStatus(), biggest_crate.WriteName("Huge crate"));

  {
    Crate::StreamEncoder medium_crate = biggest_crate.GetSmallerCratesEncoder();
    ASSERT_EQ(OkStatus(), medium_crate.WriteName("Medium crate"));
    {
      Crate::StreamEncoder small_crate = medium_crate.GetSmallerCratesEncoder();
      ASSERT_EQ(OkStatus(), small_crate.WriteName("Small crate"));
    }
    {
      Crate::StreamEncoder tiny_crate = medium_crate.GetSmallerCratesEncoder();
      ASSERT_EQ(OkStatus(), tiny_crate.WriteName("Tiny crate"));
    }
  }

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // crate.name
    0x0a, 0x0a, 'H', 'u', 'g', 'e', ' ', 'c', 'r', 'a', 't', 'e',
    // crate.smaller_crate[0]
    0x12, 0x2b,
    // crate.smaller_crate[0].name
    0x0a, 0x0c, 'M', 'e', 'd', 'i', 'u', 'm', ' ', 'c', 'r', 'a', 't', 'e',
    // crate.smaller_crate[0].smaller_crate[0]
    0x12, 0x0d,
    // crate.smaller_crate[0].smaller_crate[0].name
    0x0a, 0x0b, 'S', 'm', 'a', 'l', 'l', ' ', 'c', 'r', 'a', 't', 'e',
    // crate.smaller_crate[0].smaller_crate[1]
    0x12, 0x0c,
    // crate.smaller_crate[0].smaller_crate[1].name
    0x0a, 0x0a, 'T', 'i', 'n', 'y', ' ', 'c', 'r', 'a', 't', 'e',
  };
  // clang-format on

  ConstByteSpan result(biggest_crate);
  ASSERT_EQ(biggest_crate.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, ConstrainedFull) {
  // Write and expect non-packed since that's the worst-case size.

  // clang-format off
  constexpr auto expected_proto = bytes::Array<
    // uint32s[], v={0xdeadbeef, 0x2b84f00d}
    ToByte<FieldKey(1, WireType::kFixed32)>(), 0xef, 0xbe, 0xad, 0xde,
    ToByte<FieldKey(1, WireType::kFixed32)>(), 0x0d, 0xf0, 0x84, 0x2b
  >();
  // clang-format on

  std::byte encode_buffer[ConstrainedRepeatedTest::kMaxEncodedSizeBytes];

  // In this test, we expect to exactly utilize the encoding buffer.
  EXPECT_EQ(ConstrainedRepeatedTest::kMaxEncodedSizeBytes,
            expected_proto.size());

  stream::MemoryWriter writer(encode_buffer);
  ConstrainedRepeatedTest::StreamEncoder encoder(writer, ByteSpan());

  PW_TEST_ASSERT_OK(encoder.WriteFixed32s(0xdeadbeef));
  PW_TEST_ASSERT_OK(encoder.WriteFixed32s(0x2b84f00d));

  PW_TEST_ASSERT_OK(encoder.status());
  EXPECT_SEQ_EQ(writer.WrittenData(), expected_proto);
}

TEST(CodegenRepeated, NonPackedScalar) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 32];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  for (uint32_t i = 0; i < 4; ++i) {
    ASSERT_EQ(OkStatus(), repeated_test.WriteUint32s(i * 16));
  }

  for (uint32_t i = 0; i < 4; ++i) {
    ASSERT_EQ(OkStatus(), repeated_test.WriteFixed32s(i * 16));
  }

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // uint32s[], v={0, 16, 32, 48}
    0x08, 0x00,
    0x08, 0x10,
    0x08, 0x20,
    0x08, 0x30,
    // fixed32s[]. v={0, 16, 32, 48}
    0x35, 0x00, 0x00, 0x00, 0x00,
    0x35, 0x10, 0x00, 0x00, 0x00,
    0x35, 0x20, 0x00, 0x00, 0x00,
    0x35, 0x30, 0x00, 0x00, 0x00,
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, PackedScalar) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 32];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  constexpr uint32_t values[] = {0, 16, 32, 48};
  ASSERT_EQ(OkStatus(), repeated_test.WriteUint32s(values));
  ASSERT_EQ(OkStatus(), repeated_test.WriteFixed32s(values));

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // uint32s[], v={0, 16, 32, 48}
    0x0a, 0x04,
    0x00,
    0x10,
    0x20,
    0x30,
    // fixed32s[]. v={0, 16, 32, 48}
    0x32, 0x10,
    0x00, 0x00, 0x00, 0x00,
    0x10, 0x00, 0x00, 0x00,
    0x20, 0x00, 0x00, 0x00,
    0x30, 0x00, 0x00, 0x00,
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, PackedBool) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 8];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  constexpr bool values[] = {true, false, true, true, false};
  ASSERT_EQ(OkStatus(), repeated_test.WriteBools(span(values)));

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // bools[], v={true, false, true, true, false}
    0x3a, 0x05, 0x01, 0x00, 0x01, 0x01, 0x00,
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, PackedScalarVector) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 32];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  const pw::Vector<uint32_t, 4> values = {0, 16, 32, 48};
  ASSERT_EQ(OkStatus(), repeated_test.WriteUint32s(values));
  ASSERT_EQ(OkStatus(), repeated_test.WriteFixed32s(values));

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // uint32s[], v={0, 16, 32, 48}
    0x0a, 0x04,
    0x00,
    0x10,
    0x20,
    0x30,
    // fixed32s[]. v={0, 16, 32, 48}
    0x32, 0x10,
    0x00, 0x00, 0x00, 0x00,
    0x10, 0x00, 0x00, 0x00,
    0x20, 0x00, 0x00, 0x00,
    0x30, 0x00, 0x00, 0x00,
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, PackedEnum) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 8];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  constexpr Enum values[] = {Enum::RED, Enum::GREEN, Enum::AMBER, Enum::RED};
  ASSERT_EQ(repeated_test.WriteEnums(span(values)), OkStatus());

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // enums[], v={RED, GREEN, AMBER, RED}
    0x4a, 0x04, 0x00, 0x02, 0x01, 0x00
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, PackedEnumVector) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 8];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  const pw::Vector<Enum, 4> values = {
      Enum::RED, Enum::GREEN, Enum::AMBER, Enum::RED};
  ASSERT_EQ(repeated_test.WriteEnums(values), OkStatus());

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    // enums[], v={RED, GREEN, AMBER, RED}
    0x4a, 0x04, 0x00, 0x02, 0x01, 0x00
  };
  // clang-format on

  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, NonScalar) {
  std::byte encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues + 32];

  stream::MemoryWriter writer(encode_buffer);
  RepeatedTest::StreamEncoder repeated_test(writer, ByteSpan());
  constexpr const char* strings[] = {"the", "quick", "brown", "fox"};
  for (const char* s : strings) {
    ASSERT_EQ(OkStatus(), repeated_test.WriteStrings(s));
  }

  constexpr uint8_t expected_proto[] = {
      0x1a, 0x03, 't', 'h', 'e', 0x1a, 0x5, 'q',  'u', 'i', 'c', 'k',
      0x1a, 0x5,  'b', 'r', 'o', 'w',  'n', 0x1a, 0x3, 'f', 'o', 'x'};
  ConstByteSpan result = writer.WrittenData();
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(CodegenRepeated, Message) {
  constexpr size_t kNumStructs = 3;

  std::byte
      encode_buffer[RepeatedTest::kMaxEncodedSizeBytesWithoutValues +
                    kNumStructs * test::pwpb::Struct::kMaxEncodedSizeBytes];

  RepeatedTest::MemoryEncoder repeated_test(encode_buffer);
  for (uint32_t i = 0; i < kNumStructs; ++i) {
    auto structs = repeated_test.GetStructsEncoder();
    ASSERT_EQ(OkStatus(), structs.WriteOne(i * 1));
    ASSERT_EQ(OkStatus(), structs.WriteTwo(i * 2));
  }

  // clang-format off
  constexpr uint8_t expected_proto[] = {
    0x2a, 0x04, 0x08, 0x00, 0x10, 0x00, 0x2a, 0x04, 0x08,
    0x01, 0x10, 0x02, 0x2a, 0x04, 0x08, 0x02, 0x10, 0x04};
  // clang-format on

  ConstByteSpan result(repeated_test);
  ASSERT_EQ(repeated_test.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(Codegen, Proto2) {
  std::byte encode_buffer[Foo::kMaxEncodedSizeBytesWithoutValues + 8];

  Foo::MemoryEncoder foo(encode_buffer);
  ASSERT_EQ(OkStatus(), foo.WriteInteger(3));

  {
    constexpr std::byte data[] = {
        std::byte(0xde), std::byte(0xad), std::byte(0xbe), std::byte(0xef)};
    Bar::StreamEncoder bar = foo.GetBarEncoder();
    ASSERT_EQ(OkStatus(), bar.WriteData(data));
  }

  constexpr uint8_t expected_proto[] = {
      0x08, 0x03, 0x1a, 0x06, 0x0a, 0x04, 0xde, 0xad, 0xbe, 0xef};

  ConstByteSpan result(foo);
  ASSERT_EQ(foo.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(Codegen, Import) {
  std::byte encode_buffer[Period::kMaxEncodedSizeBytes];

  Period::MemoryEncoder period(encode_buffer);
  {
    imported::Timestamp::StreamEncoder start = period.GetStartEncoder();
    ASSERT_EQ(OkStatus(), start.WriteSeconds(1589501793));
    ASSERT_EQ(OkStatus(), start.WriteNanoseconds(511613110));
  }

  {
    imported::Timestamp::StreamEncoder end = period.GetEndEncoder();
    ASSERT_EQ(OkStatus(), end.WriteSeconds(1589501841));
    ASSERT_EQ(OkStatus(), end.WriteNanoseconds(490367432));
  }

  EXPECT_EQ(period.status(), OkStatus());
}

TEST(Codegen, NonPigweedPackage) {
  namespace Packed = ::non::pigweed::package::name::pwpb::Packed;

  std::byte encode_buffer[Packed::kMaxEncodedSizeBytesWithoutValues + 8];
  std::array<const int64_t, 2> repeated = {0, 1};
  stream::MemoryWriter writer(encode_buffer);
  Packed::StreamEncoder packed(writer, ByteSpan());
  ASSERT_EQ(OkStatus(), packed.WriteRep(span<const int64_t>(repeated)));
  ASSERT_EQ(OkStatus(), packed.WritePacked("packed"));

  EXPECT_EQ(packed.status(), OkStatus());
}

TEST(Codegen, MemoryToStreamConversion) {
  std::byte encode_buffer[IntegerMetadata::kMaxEncodedSizeBytes];
  IntegerMetadata::MemoryEncoder metadata(encode_buffer);
  IntegerMetadata::StreamEncoder& streamed_metadata = metadata;
  EXPECT_EQ(streamed_metadata.WriteBits(3), OkStatus());

  constexpr uint8_t expected_proto[] = {0x08, 0x03};

  ConstByteSpan result(metadata);
  ASSERT_EQ(metadata.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(Codegen, OverlayConversion) {
  std::byte encode_buffer[BaseMessage::kMaxEncodedSizeBytes +
                          Overlay::kMaxEncodedSizeBytes];
  BaseMessage::MemoryEncoder base(encode_buffer);
  Overlay::StreamEncoder& overlay =
      StreamEncoderCast<Overlay::StreamEncoder>(base);
  EXPECT_EQ(overlay.WriteHeight(15), OkStatus());
  EXPECT_EQ(base.WriteLength(7), OkStatus());

  constexpr uint8_t expected_proto[] = {0x10, 0x0f, 0x08, 0x07};

  ConstByteSpan result(base);
  ASSERT_EQ(base.status(), OkStatus());
  EXPECT_EQ(result.size(), sizeof(expected_proto));
  EXPECT_EQ(std::memcmp(result.data(), expected_proto, sizeof(expected_proto)),
            0);
}

TEST(Codegen, EnumToString) {
  EXPECT_STREQ(test::pwpb::BoolToString(test::pwpb::Bool::kTrue), "TRUE");
  EXPECT_STREQ(test::pwpb::BoolToString(test::pwpb::Bool::kFalse), "FALSE");
  EXPECT_STREQ(test::pwpb::BoolToString(test::pwpb::Bool::kFileNotFound),
               "FILE_NOT_FOUND");
}

TEST(Codegen, EnumToStringInvalid) {
  constexpr auto kInvalid = static_cast<test::pwpb::Bool>(12893);

  EXPECT_STREQ(test::pwpb::BoolToString(kInvalid), "");
  EXPECT_STREQ(test::pwpb::BoolToString(kInvalid, "okay"), "okay");
  EXPECT_EQ(test::pwpb::BoolToString(kInvalid, nullptr), nullptr);
}

TEST(Codegen, NestedEnumToString) {
  EXPECT_STREQ(test::pwpb::Pigweed::Pigweed::BinaryToString(
                   test::pwpb::Pigweed::Pigweed::Binary::kZero),
               "ZERO");
  EXPECT_STREQ(test::pwpb::Pigweed::Pigweed::BinaryToString(
                   test::pwpb::Pigweed::Pigweed::Binary::kOne),
               "ONE");
}

TEST(Codegen, NestedEnumToStringInvalid) {
  constexpr auto kInvalid =
      static_cast<test::pwpb::Pigweed::Pigweed::Binary>(12893);

  EXPECT_STREQ(test::pwpb::Pigweed::Pigweed::BinaryToString(kInvalid), "");
  EXPECT_STREQ(test::pwpb::Pigweed::Pigweed::BinaryToString(kInvalid, "okay"),
               "okay");
  EXPECT_STREQ(test::pwpb::Pigweed::Pigweed::BinaryToString(kInvalid, nullptr),
               nullptr);
}

TEST(Codegen, EnumValuesArray) {
  EXPECT_EQ(test::pwpb::kBoolValues.size(), 3u);

  EXPECT_TRUE(Contains(test::pwpb::kBoolValues, test::pwpb::Bool::kTrue));
  EXPECT_TRUE(Contains(test::pwpb::kBoolValues, test::pwpb::Bool::kFalse));
  EXPECT_TRUE(
      Contains(test::pwpb::kBoolValues, test::pwpb::Bool::kFileNotFound));

  for (const test::pwpb::Bool value : test::pwpb::kBoolValues) {
    EXPECT_TRUE(test::pwpb::IsValidBool(value));
  }
}

// Demonstrate how the k*Values array can be used in a constexpr context to,
// e.g., produce a constexpr array of enum name strings.

template <auto ToString, typename EnumType, size_t kNumValues>
constexpr std::array<std::string_view, kNumValues> EnumToNames(
    const std::array<EnumType, kNumValues>& values) {
  std::array<std::string_view, kNumValues> result{};
  for (size_t i = 0; i < kNumValues; ++i) {
    result[i] = ToString(values[i], "");
  }
  return result;
}

constexpr auto kBoolNames =
    EnumToNames<test::pwpb::BoolToString>(test::pwpb::kBoolValues);

TEST(Codegen, EnumNamesArray) {
  EXPECT_EQ(kBoolNames.size(), 3u);

  EXPECT_TRUE(Contains(kBoolNames, "TRUE"));
  EXPECT_TRUE(Contains(kBoolNames, "FALSE"));
  EXPECT_TRUE(Contains(kBoolNames, "FILE_NOT_FOUND"));
}

}  // namespace
}  // namespace pw::protobuf
