#pragma once
#include "fs/IStreamSink.h"
#include "tl/memory_buffer.h"
#include "fs/Api.h"
#include "tl/ptr.h"

namespace fs
{
//////////////////////////////////////////////////////////////////////////

class FS_API DeflateStreamSink final: public IStreamSink
{
public:
	explicit DeflateStreamSink(IStreamSink& sink); //non owning
	explicit DeflateStreamSink(tl::unique_ref<IStreamSink> sink); //owning
	~DeflateStreamSink() override;

	//compression level - 0 to 9
	void setCompressionLevel(uint8_t level);

	tl::optional<Error> getLastError() const override;
	size_t write(tl::span<const uint8_t> data) override;

	size_t getPreferredBufferSize() const override;

	uint64_t getSize() const override;

	//Finish is also called by the destructor
	void finish();
	tl::unique_ref<IStreamSink> finishAndExtract();

private:
	tl::unique_ptr<IStreamSink> m_ownedSink;
	IStreamSink& m_sink;

	uint8_t m_level = 6;
	mutable tl::optional<Error> m_optLastError;

	void initializeDeflate();
	bool flush(bool finalize);

	struct ZLib;
	tl::unique_ptr<ZLib> m_zlib;

	tl::memory_buffer m_buffer;
	size_t m_bufferOffset = 0;
	uint64_t m_size = 0;

	tl::memory_buffer m_outBuffer;
	bool m_isFinished = false;
};

//////////////////////////////////////////////////////////////////////////
}
