/*
 * Copyright 2015 - 2025 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 https://mozilla.org/MPL/2.0/.
 */

#pragma once

#include "concepts.hpp"
#include "error.hpp"
#include "types.hpp"
#include "writer.hpp"

namespace ox {

template<typename T>
concept Reader_c = requires(T v) {
	{v.peek()} -> ox::same_as<ox::Result<char>>;
	{v.read(static_cast<char*>(nullptr), static_cast<std::size_t>(0))} -> ox::same_as<ox::Result<std::size_t>>;
	{v.seekg(static_cast<int64_t>(0))} -> ox::same_as<ox::Error>;
	{v.seekg(static_cast<std::size_t>(0), ios_base::beg)} -> ox::same_as<ox::Error>;
	{v.tellg()} -> ox::same_as<ox::Result<std::size_t>>;
};

class Reader_v {
	public:
		virtual constexpr ~Reader_v() noexcept = default;
		virtual constexpr ox::Result<char> peek() const noexcept = 0;
		virtual constexpr ox::Result<std::size_t> read(char*, std::size_t) noexcept = 0;
		virtual constexpr ox::Result<std::size_t> tellg() noexcept = 0;
		virtual constexpr ox::Error seekg(std::size_t) noexcept = 0;
		virtual constexpr ox::Error seekg(int64_t, ios_base::seekdir) = 0;
};

template<Reader_c T>
class ReaderT: public Reader_v {
	private:
		T m_reader{};
	public:
		template<typename ...Args>
		constexpr explicit ReaderT(Args&&... args) noexcept: m_reader(args...) {
		}
		constexpr ox::Result<char> peek() const noexcept override {
			return m_reader.peek();
		}
		constexpr ox::Result<std::size_t> read(char *v, std::size_t cnt) noexcept override {
			return m_reader.read(v, cnt);
		}
		constexpr ox::Error seekg(std::size_t p) noexcept override {
			return m_reader.seekg(p);
		}
		constexpr ox::Error seekg(int64_t p, ios_base::seekdir sd) noexcept override {
			return m_reader.seekg(p, sd);
		}
		constexpr ox::Result<std::size_t> tellg() noexcept override {
			return m_reader.tellg();
		}
};

}
