/*
 * 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 "ArchiveBase.hpp"
#include "ArchiveConfiguration.hpp"
#include "IArchiveWriter.hpp"

namespace OpenVulkano
{
	class MultiPartArchiveWriter;

	class ArchiveWriter final : public ArchiveBase, public IArchiveWriter
	{
		friend MultiPartArchiveWriter;
		friend ArchiveStreamBufferWriter;

		ArchiveConfiguration m_archiveConfig;
		size_t m_bytesWritten = 0;
		ArchiveOStream::ASBufferPtr m_asBuffer = nullptr;
		bool m_lastCompressed = true;
		std::function<bool(const FileDescription&)> m_shouldCompress;

	public:
		ArchiveWriter(const char* fileName, const std::shared_ptr<spdlog::logger>& logger = nullptr)
				: ArchiveWriter(fileName, ArchiveConfiguration::FromFileName(fileName), logger)
		{}

		ArchiveWriter(const char* fileName, ArchiveConfiguration archiveConfiguration, const std::shared_ptr<spdlog::logger>& logger = nullptr);

		~ArchiveWriter() override;

		[[nodiscard]] size_t GetTotalWrittenBytes() const { return m_bytesWritten; }

		bool AddFile(const FileDescription& description, const void* buffer) override;
		bool AddFile(const FileDescription& description, const std::vector<std::pair<const void*, size_t>>& buffers) override;
		bool AddFile(const char* fileName, const char* inArchiveName) override;
		[[nodiscard]] ArchiveOStream AddFileStream(const FileDescription& description) override;

		void SetShouldCompressFunction(const std::function<bool(const FileDescription&)>& shouldComp) override { m_shouldCompress = shouldComp; }

	private:
		void WriteHeader(const FileDescription& fileDescription);

		void SetUncompressed();

		void SetCompressed();
	};
}