/*
 * 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 "AR/ArSession.hpp"
#include "ArPlaybackReader.hpp"
#include "Math/Timestamp.hpp"

namespace OpenVulkano::AR::Playback
{
class ArSessionPlayback final : public ArSession, public std::enable_shared_from_this<ArSessionPlayback>
	{
	public:
		ArSessionPlayback(const std::string& recordingPath, bool autoAdvance, bool loadImages, bool loadDepth);

		~ArSessionPlayback() override;

		void Start() override;

		void Stop() override;

		void Pause() override;

		[[nodiscard]] std::shared_ptr<ArFrame> GetFrame() override;

		[[nodiscard]] ArSessionType GetSessionType() override { return ArSessionType::PLAYBACK; }

		[[nodiscard]] ArType GetArType() override;

		[[nodiscard]] const std::string& GetPlaybackPath() const { return recordingPath; }

		[[nodiscard]] bool IsLoadColorEnabled() const { return loadImages; }
		[[nodiscard]] bool IsLoadDepthEnabled() const { return loadDepth; }

		void SetRenderer(IRenderer* renderer) override;
		
		Event<double> OnPlaybackProgress;

	protected:
		Scene::Texture* MakeTexture(OpenVulkano::AR::ArFrame* frame) override;

		void ReturnTexture(Scene::Texture *texture) override;

	private:
		void ReadWorker();


		Math::Timestamp lastTimestamp;
		const std::string recordingPath;
		const bool autoAdvance, loadImages, loadDepth;
		ArPlaybackReader playbackReader;
		ArTrackingState m_lastTrackingState = ArTrackingState::UNKNOWN;

		std::atomic_bool m_frameConsumed = true;
		std::shared_ptr<ArFrame> m_nextFrame;
		std::thread m_playbackReaderThread;

		std::vector<Scene::Texture*> m_textureCache;
	};
}
