#pragma once

#include <godot_cpp/variant/packed_byte_array.hpp>
#include <godot_cpp/variant/string.hpp>
#include <stdexcept>
#include <vector>

namespace blitz {
namespace protocol {

class PlayerInfo;

class ByteBuffer {
  private:
	godot::PackedByteArray m_Buffer;
	std::size_t m_ReadOffset;

  public:
	class ReadError : public std::runtime_error {
	  public:
		ReadError(const std::string& msg) : std::runtime_error(msg) {}
	};

	ByteBuffer(godot::PackedByteArray&& a_Buffer) : m_Buffer(std::move(a_Buffer)), m_ReadOffset(0) {}
	ByteBuffer() : m_ReadOffset(0) {
		m_Buffer.resize(0);
	}

	const godot::PackedByteArray& GetByteArray() const {
		return m_Buffer;
	}

	godot::PackedByteArray& GetByteArray() {
		return m_Buffer;
	}

	// Integers
	ByteBuffer& operator<<(int8_t a_Data);
	ByteBuffer& operator>>(int8_t& a_Data);
	ByteBuffer& operator<<(uint8_t a_Data);
	ByteBuffer& operator>>(uint8_t& a_Data);

	ByteBuffer& operator<<(int16_t a_Data);
	ByteBuffer& operator>>(int16_t& a_Data);
	ByteBuffer& operator<<(uint16_t a_Data);
	ByteBuffer& operator>>(uint16_t& a_Data);

	ByteBuffer& operator<<(int32_t a_Data);
	ByteBuffer& operator>>(int32_t& a_Data);
	ByteBuffer& operator<<(uint32_t a_Data);
	ByteBuffer& operator>>(uint32_t& a_Data);

	ByteBuffer& operator<<(int64_t a_Data);
	ByteBuffer& operator>>(int64_t& a_Data);
	ByteBuffer& operator<<(uint64_t a_Data);
	ByteBuffer& operator>>(uint64_t& a_Data);

	ByteBuffer& operator<<(float a_Data);
	ByteBuffer& operator>>(float& a_Data);
	ByteBuffer& operator<<(double a_Data);
	ByteBuffer& operator>>(double& a_Data);

	ByteBuffer& operator<<(const godot::String& a_Data);
	ByteBuffer& operator>>(godot::String& a_Data);

	ByteBuffer& operator<<(const godot::Vector3& a_Data);
	ByteBuffer& operator>>(godot::Vector3& a_Data);

	template <typename T>
	ByteBuffer& operator<<(const std::vector<T>& a_Data) {
		*this << static_cast<std::uint32_t>(a_Data.size());
		for (const T& data : a_Data) {
			*this << data;
		}
		return *this;
	}

	template <typename T>
	ByteBuffer& operator>>(std::vector<T>& a_Data) {
		std::uint32_t arraySize;
		*this >> arraySize;
		a_Data.resize(arraySize);
		for (std::uint32_t i = 0; i < arraySize; i++) {
			*this >> a_Data[i];
		}
		return *this;
	}

	ByteBuffer& operator<<(const PlayerInfo& a_Data);
	ByteBuffer& operator>>(PlayerInfo& a_Data);
};

}  // namespace protocol
}  // namespace blitz
