// 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.

#include "cartridge/binary_reader.h"

#include <algorithm>
#include <bit>
#include <cstring>

namespace cartridge {

BinaryReader::BinaryReader(std::span<const uint8_t> data,
                           const Endian endian)
    : _data(data), _endian(endian), _index(0) {}

void BinaryReader::seek(const int offset, const SeekOrigin origin) {
  switch (origin) {
  case SeekOrigin::Begin:
    _index = offset;
    break;
  case SeekOrigin::Current:
    _index += offset;
    break;
  case SeekOrigin::End:
    _index = _data.size() - offset;
    break;
  }
}

uint8_t BinaryReader::getByte() {
  if (_index >= _data.size())
    throw std::out_of_range("getByte out of range");
  return _data[_index++];
}

int16_t BinaryReader::getShort() { return readInt<int16_t>(2); }

uint16_t BinaryReader::getUShort() { return readInt<uint16_t>(2); }

int32_t BinaryReader::getLong() { return readInt<int32_t>(4); }

uint32_t BinaryReader::getULong() { return readInt<uint32_t>(4); }

double BinaryReader::getDouble() {
  if (_index + 8 > _data.size())
    throw std::out_of_range("getDouble out of range");
  double value;
  std::memcpy(&value, &_data[_index], 8);
  if ((_endian == Endian::Little) != isSystemLittleEndian()) {
    swapBytes(reinterpret_cast<uint8_t *>(&value), 8);
  }
  _index += 8;
  return value;
}

std::string BinaryReader::getASCIIZ() {
  std::string result;
  uint8_t byte = 0;
  do {
    byte = getByte();
    if (byte != 0)
      result += static_cast<char>(byte);
  } while (byte != 0);
  return result;
}

bool BinaryReader::isSystemLittleEndian() {
  return std::endian::native == std::endian::little;
}

void BinaryReader::swapBytes(uint8_t *data, size_t size) {
  std::ranges::reverse(data, data + size);
}

} // namespace cartridge
