// MIT License
// Copyright (c) 2026 by Peter Siegmund (mars3142)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
#include <span>

namespace cartridge {

enum class SeekOrigin { Begin, Current, End };

enum class Endian { Little, Big };

class BinaryReader {
public:
  explicit BinaryReader(std::span<const uint8_t> data,
                        Endian endian = Endian::Little);

  void seek(int offset, SeekOrigin origin);
  [[nodiscard]] uint8_t getByte();
  [[nodiscard]] int16_t getShort();
  [[nodiscard]] uint16_t getUShort();
  [[nodiscard]] int32_t getLong();
  [[nodiscard]] uint32_t getULong();
  [[nodiscard]] double getDouble();
  [[nodiscard]] std::string getASCIIZ();
  [[nodiscard]] std::span<const uint8_t> data() const { return _data; }

private:
  template <typename T> [[nodiscard]] T readInt(size_t size);
  [[nodiscard]] static bool isSystemLittleEndian();
  static void swapBytes(uint8_t *data, size_t size);

  std::span<const uint8_t> _data;
  Endian _endian;
  size_t _index;
};

template <typename T> T BinaryReader::readInt(const size_t size) {
  if (_index + size > _data.size())
    throw std::out_of_range("readInt out of range");
  T value = 0;
  if (_endian == Endian::Little) {
    for (size_t i = 0; i < size; ++i) {
      value |= static_cast<T>(_data[_index + i]) << (8 * i);
    }
  } else {
    for (size_t i = 0; i < size; ++i) {
      value = (value << 8) | _data[_index + i];
    }
  }
  _index += size;
  return value;
}

} // namespace cartridge
