/*! \file pichunkstream.h
 * \brief Binary markup serializator
*/
/*
	PIP - Platform Independent Primitives
	Binary markup serializator
	Ivan Pelipenko peri4ko@yandex.ru

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef PICHUNKSTREAM_H
#define PICHUNKSTREAM_H

#include "pibytearray.h"


class PIP_EXPORT PIChunkStream
{
public:

	//! Version of data packing. Read-access %PIChunkStream automatic detect version, but write-access
	//! %PIChunkStream by default write in new version, be careful!
	enum Version {
		Version_1 /*! First, old version */,
		Version_2 /*! Second, more optimized version */ = 2,
	};

	//! Contructs stream for read from "data"
	PIChunkStream(const PIByteArray & data): version_(Version_2) {setSource(data);}

	//! Contructs stream for read or write to/from "data", or empty stream for write
	PIChunkStream(PIByteArray * data = 0, Version v = Version_2): version_(v) {setSource(data);}

	//! Contructs empty stream for write with version \"v\"
	PIChunkStream(Version v): version_(v) {setSource(0);}
	
	~PIChunkStream();
	
	template <typename T>
	struct Chunk {
		Chunk(int i, const T & d): id(i), data(d) {}
		int id;
		T data;
	};
	template <typename T>
	struct ChunkConst {
		ChunkConst(int i, const T & d): id(i), data(d) {}
		int id;
		const T & data;
	};
	
	//! Returns chunk with ID "id" and value "data" for write to stream
	template <typename T> static ChunkConst<T> chunk(int id, const T & data) {return ChunkConst<T>(id, data);}

	//! Add data to this chunk strean with ID "id" and value "data"
	template <typename T> PIChunkStream & add(int id, const T & data) {*this << ChunkConst<T>(id, data); return *this;}

	//! Extract %PIByteArray from "data" and set it current stream.
	//! If "read_all" then call \a readAll() after extract.
	//! Returns if has data to read.
	bool extract(PIByteArray & data, bool read_all = false);

	void setSource(const PIByteArray & data);
	void setSource(PIByteArray * data);
	
	//! Returns internal buffer with written data
	PIByteArray data() const {return tmp_data;}
	
	//! Returns if there is end of stream
	bool atEnd() const {return data_->size_s() <= 1;}

	//! Returns stream version
	Version version() const {return (Version)version_;}
	

	//! Read one chunk from stream and returns its ID
	int read();

	//! Read all chunks from stream. This function just index input data
	void readAll();
	
	//! Returns last readed chunk ID
	int getID() {return last_id;}
	
	//! Returns value of last readed chunk
	template <typename T>
	T getData() const {T ret; PIByteArray s(last_data); s >> ret; return ret;}

	//! Place value of last readed chunk into \"v\"
	template <typename T>
	void get(T & v) const {v = getData<T>();}

	//! Place value of chunk with id \"id\" into \"v\". You should call \a readAll() before using this function!
	template <typename T>
	const PIChunkStream & get(int id, T & v) const {
		PIPair<int, int> pos = data_map.value(id);
		if (pos.first < 0 || pos.second == 0) return *this;
		PIByteArray ba(data_->data(pos.first), pos.second);
		if (!ba.isEmpty())
			ba >> v;
		return *this;
	}

private:
	void _init();
	
	static uint readVInt(PIByteArray & s, uchar * bytes = 0);
	static void writeVInt(PIByteArray & s, uint val);
	static int peekVInt(Version version_, PIByteArray * data_, int pos, PIByteArray & hdr, uint & ret);

	int last_id;
	uchar version_;
	PIByteArray * data_, last_data, tmp_data;
	PIMap<int, PIPair<int, int>> data_map;
	
	template <typename T> friend PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c);
	template <typename T> friend PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::ChunkConst<T> & c);
};

template <typename T>
PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c) {
	PIByteArray ba;
	ba << c.data;
	switch (s.version_) {
	case PIChunkStream::Version_1:
		(*(s.data_)) << c.id << ba;
		break;
	case PIChunkStream::Version_2:
		if (s.data_->isEmpty())
			(*(s.data_)) << uchar(uchar(s.version_) | 0x80);
		PIChunkStream::writeVInt(*(s.data_), c.id);
		PIChunkStream::writeVInt(*(s.data_), ba.size());
		s.data_->append(ba);
		break;
	default: break;
	}
	return s;
}
template <typename T>
PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::ChunkConst<T> & c) {
	PIByteArray ba;
	ba << c.data;
	switch (s.version_) {
	case PIChunkStream::Version_1:
		(*(s.data_)) << c.id << ba;
		break;
	case PIChunkStream::Version_2:
		if (s.data_->isEmpty())
			(*(s.data_)) << uchar(uchar(s.version_) | 0x80);
		PIChunkStream::writeVInt(*(s.data_), c.id);
		PIChunkStream::writeVInt(*(s.data_), ba.size());
		s.data_->append(ba);
		break;
	default: break;
	}
	return s;
}

#endif // PICHUNKSTREAM_H
