/*
 * 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 "IO/Archive/ArchiveReader.hpp"
#include "IO/Files/Pfm.hpp"
#include "IO/Files/Pnm.hpp"
#include <string>
#include <fstream>

namespace OpenVulkano::AR::Playback
{
	struct DepthImage
	{
		PfmImage depth;
		PnmImage confidence;
	};

	struct ColorImg
	{
		std::shared_ptr<uint8_t> dataPtr;
		uint8_t* data;
		int cols, rows, channels;
	};

	class ArPlaybackReader final
	{
		static constexpr std::string_view TAR_EXTENSIONS_REGEX = R"(\.(tar(\.gz|\.bz2)?|tgz|tbz|tb2|tbz2))";

		ArchiveReader m_archiveMetadata, m_archiveColor, m_archiveDepth, m_archiveConfidence;
		size_t m_depthTotalSize = 0, m_depthReadSize = 0;
		
	public:
		ArPlaybackReader(const std::string& recDir)
		{
			std::string extensions = R"((_\d+|\.part\d+)?)" + std::string(TAR_EXTENSIONS_REGEX);
			m_archiveMetadata.Open(recDir, ".*meta(data)?" + extensions);
			m_archiveColor.Open(recDir, ".*(color|image)" + extensions);
			m_archiveDepth.Open(recDir, ".*depth" + extensions, &m_depthTotalSize);
			m_archiveConfidence.Open(recDir, ".*conf(idence)?" + extensions);
		}

		int GetNextFrameId()
		{
			std::string name = m_archiveMetadata.GetNextDescription().path;
			return std::stoi(name.substr(0, name.length() - 5));
		}

		Array<char> ReadMetadata()
		{
			return std::move(m_archiveMetadata.GetNextFile()->second);
		}

		ColorImg ReadColorImage();

		DepthImage ReadDepthImage()
		{
			DepthImage img;
			size_t& depthRead = m_depthReadSize;
			m_archiveDepth.GetNextFileAsStream([&img, &depthRead](const FileDescription& desc, std::istream& stream) { img.depth.Read(stream); depthRead += desc.size + 1000; });
			m_archiveConfidence.GetNextFileAsStream([&img](const FileDescription&, std::istream& stream) { img.confidence.Read(stream); });
			
			return img;
		}
		
		[[nodiscard]] double GetProgress() const
		{
			return static_cast<double>(m_depthReadSize) / static_cast<double>(m_depthTotalSize);
		}

		[[nodiscard]] bool HasNext() const
		{
			return m_archiveMetadata.HasNext() && m_archiveDepth.HasNext() && m_archiveConfidence.HasNext() && m_archiveColor.HasNext();
		}
	};
}
