/*
 * Copyright 2015 - 2022 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/std/error.hpp>
#include <ox/std/types.hpp>

namespace ox {

template<typename T>
class FieldBitmapReader {
	protected:
		T m_map = nullptr;
		std::size_t m_mapLen = 0;

	public:
		constexpr FieldBitmapReader(T map, std::size_t maxLen) noexcept;

		constexpr Result<bool> get(std::size_t i) const noexcept;

		constexpr void setFields(int) noexcept;

		constexpr void setMaxLen(int) noexcept;

		[[nodiscard]]
		constexpr int64_t getMaxLen() const noexcept;

};

template<typename T>
constexpr FieldBitmapReader<T>::FieldBitmapReader(T map, std::size_t maxLen) noexcept {
	m_map = map;
	m_mapLen = maxLen;
}

template<typename T>
constexpr Result<bool> FieldBitmapReader<T>::get(std::size_t i) const noexcept {
	if (i / 8 < m_mapLen) {
		return (m_map[i / 8] >> (i % 8)) & 1;
	} else {
		return OxError(MC_PRESENCEMASKOUTBOUNDS);
	}
}

template<typename T>
constexpr void FieldBitmapReader<T>::setFields(int fields) noexcept {
	m_mapLen = static_cast<std::size_t>((fields / 8 + 1) - (fields % 8 == 0));
}

template<typename T>
constexpr void FieldBitmapReader<T>::setMaxLen(int maxLen) noexcept {
	m_mapLen = static_cast<std::size_t>(maxLen);
}

template<typename T>
constexpr int64_t FieldBitmapReader<T>::getMaxLen() const noexcept {
	return static_cast<int64_t>(m_mapLen);
}

extern template class FieldBitmapReader<uint8_t*>;
extern template class FieldBitmapReader<const uint8_t*>;

class FieldBitmap: public FieldBitmapReader<uint8_t*> {

	public:
		constexpr FieldBitmap(uint8_t *map, std::size_t maxLen) noexcept;

		constexpr Error set(std::size_t i, bool on) noexcept;

};

constexpr FieldBitmap::FieldBitmap(uint8_t *map, std::size_t maxLen) noexcept: FieldBitmapReader<uint8_t*>(map, maxLen) {
}

constexpr Error FieldBitmap::set(std::size_t i, bool on) noexcept {
	if (i / 8 < m_mapLen) {
		if (on) {
			m_map[i / 8] |= 1 << (i % 8);
		} else {
			m_map[i / 8] &= ~(1 << (i % 8));
		}
		return OxError(0);
	} else {
		return OxError(MC_PRESENCEMASKOUTBOUNDS);
	}
}

}
