/*
	PIP - Platform Independent Primitives
	Packets extractor
	Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@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/>.
*/

#include "pipacketextractor.h"


/** \class PIPacketExtractor
 * \brief Packets extractor
 * \details
 * \section PIPacketExtractor_main Synopsis
 * This class implements packet recognition by various algorithms and custom
 * validating from data stream. Stream is formed from child %PIIODevice
 * passed from contructor or with function \a setDevice().
 *
 * \section PIPacketExtractor_work Principle of work
 * %PIPacketExtractor works with child %PIIODevice. \a read and \a write
 * functions directly call child device functions. You should start threaded
 * read of \b extractor (not child device) to proper work. Extractor read data
 * from child device, try to detect packet from readed data and raise
 * \a packetReceived() event on success.
 *
 * \section PIPacketExtractor_algorithms Algorithms
 * There are 6 algorithms: \n
 * * PIPacketExtractor::None \n
 * Packet is successfully received on every read without any validation. \n \n
 * * PIPacketExtractor::Header \n
 * Wait for at least \a header() bytes + \a payloadSize(), then validate
 * header with virtual function \a validateHeader() and if it fail, shifts
 * for next 1 byte. If header is successfully validated check payload with
 * function \a validatePayload() and if it fail, shifts for next 1 byte. If
 * all validations were successful raise \a packetReceived() event. \n \n
 * * PIPacketExtractor::Footer \n
 * This algorithm similar to previous, but instead of \a header() first validate
 * \a footer() at after \a payloadSize() bytes with function \a validateFooter(). \n \n
 * * PIPacketExtractor::HeaderAndFooter \n
 * Wait for at least \a header() bytes + \a footer() bytes, then validate
 * header with virtual function \a validateHeader() and if it fail, shifts
 * for next 1 byte. If header is successfully validated check footer with
 * function \a validateFooter() and if it fail, shifts footer position for
 * next 1 byte. Then validate payload and if it fail, search header again,
 * starts from next byte of previous header. If all validations were successful
 * raise \a packetReceived() event. \n \n
 * * PIPacketExtractor::Size \n
 * Wait for at least \a packetSize() bytes, then validate packet with function
 * \a validatePayload() and if it fail, shifts for next 1 byte. If validating
 * was successfull raise \a packetReceived() event. \n \n
 * * PIPacketExtractor::Timeout \n
 * Wait for first read, then read for \a timeout() milliseconds and raise
 * \a packetReceived() event. \n
 *
 * \section PIPacketExtractor_control Control validating
 * There are three parameters:
 * * header content
 * * header size
 * * payload size
 *
 * Extractor can detect packet with compare your header with readed data.
 * It is default implementation of function \a packetHeaderValidate().
 * If header validating passed, function \a packetValidate() will be called.
 * If either of this function return \b false extractor shifts by one byte
 * and takes next header. If both functions returns \b true extractor shifts
 * by whole packet size.
 * \image html packet_detection.png
 *
 * */

REGISTER_DEVICE(PIPacketExtractor)


PIPacketExtractor::PIPacketExtractor(PIIODevice * device_, PIPacketExtractor::SplitMode mode) {
	construct();
	setDevice(device_);
	setSplitMode(mode);
}


void PIPacketExtractor::construct() {
	ret_func_header = ret_func_footer = 0;
	setPayloadSize(0);
	setTimeout(100);
#ifdef FREERTOS
	setBufferSize(512);
#else
	setBufferSize(65536);
#endif
	setDevice(0);
	setPacketSize(0);
	setSplitMode(None);
	missed = missed_packets = footerInd = 0;
	header_found = false;
}


void PIPacketExtractor::propertyChanged(const PIString &) {
	packetSize_ = property("packetSize").toInt();
	mode_ = (SplitMode)(property("splitMode").toInt());
	dataSize = property("payloadSize").toInt();
	src_header = property("header").toByteArray();
	src_footer = property("footer").toByteArray();
	packetSize_hf = src_header.size_s() + src_footer.size_s() + payloadSize();
}


void PIPacketExtractor::setDevice(PIIODevice * device_) {
	dev = device_;
	if (dev == 0) return;
}


void PIPacketExtractor::setBufferSize(int new_size) {
	buffer_size = new_size;
	buffer.resize(buffer_size);
	memset(buffer.data(), 0, buffer.size());
	setThreadedReadBufferSize(new_size);
}


void PIPacketExtractor::setPayloadSize(int size) {
	setProperty("payloadSize", size);
	dataSize = size;
	packetSize_hf = src_header.size_s() + src_footer.size_s() + payloadSize();
}


void PIPacketExtractor::setHeader(const PIByteArray & data) {
	setProperty("header", data);
	src_header = data;
	packetSize_hf = src_header.size_s() + src_footer.size_s() + payloadSize();
}


void PIPacketExtractor::setFooter(const PIByteArray & data) {
	setProperty("footer", data);
	src_footer = data;
	packetSize_hf = src_header.size_s() + src_footer.size_s() + payloadSize();
}


bool PIPacketExtractor::threadedRead(uchar * readed, int size_) {
	//piCoutObj << "readed" << size_;
	int ss;
	switch (mode_) {
	case PIPacketExtractor::None:
		if (validatePayload(readed, size_))
			packetReceived(readed, size_);
		break;
	case PIPacketExtractor::Header:
		tmpbuf.append(readed, size_);
		ss = src_header.size_s() + dataSize;
		while (tmpbuf.size_s() >= ss) {
			while (!validateHeader(src_header.data(), tmpbuf.data(), src_header.size_s())) {
				tmpbuf.pop_front();
				++missed;
				if (tmpbuf.size_s() < ss) return true;
			}
			while (!validatePayload(tmpbuf.data(src_header.size_s()), dataSize)) {
				tmpbuf.pop_front();
				++missed;
				if (tmpbuf.size_s() < ss) return true;
			}
			packetReceived(tmpbuf.data(), ss);
			tmpbuf.remove(0, ss);
		}
		break;
	case PIPacketExtractor::Footer:
		/*memcpy(buffer.data(allReaded), readed, size_);
		allReaded += size_;
		footer_ = (mode_ == PIPacketExtractor::Footer);
		while (allReaded >= packetSize_hf + addSize && allReaded > 0) {
			if (!src_header.isEmpty()) {
				if (allReaded + curInd >= buffer_size) {
					memcpy(sbuffer.data(), buffer.data(), buffer_size);
					memcpy(buffer.data(), sbuffer.data(buffer_size - packetSize_hf), allReaded);
					allReaded = packetSize_hf;
					addSize = curInd = 0;
				}
				bool brk = false;
				while (!validateHeader((uchar * )(footer_ ? src_footer.data() : src_header.data()), buffer.data(curInd + (footer_ ? dataSize : 0)), footer_ ? src_footer.size_s() : src_header.size_s())) {
					++curInd; ++missed;
					if (packetSize_hf > 0) missed_packets = missed / packetSize_hf;
					if (curInd > addSize) {
						addSize += packetSize_hf;
						brk = true;
						break;
					}
				}
				if (brk) continue;
				//memcpy(mheader.data(), buffer.data(curInd + (footer_ ? dataSize : 0)), src_header.size_s());
				if (!src_header.isEmpty()) memcpy(src_header.data(), buffer.data(curInd), src_header.size_s());
				if (!validatePayload(buffer.data(curInd + src_header.size_s()), dataSize)) {
					++curInd; ++missed;
					if (packetSize_hf > 0) missed_packets = missed / packetSize_hf;
					continue;
				}
				packetReceived(buffer.data(curInd), packetSize_hf);
				memcpy(sbuffer.data(), buffer.data(), allReaded);
				memcpy(buffer.data(), sbuffer.data(packetSize_hf + curInd), allReaded);
				allReaded -= packetSize_hf + curInd;
				curInd = addSize = 0;
			} else {
				if (dataSize == 0) {
					if (validatePayload(buffer.data(), size_))
						packetReceived(buffer.data(), size_);
					memcpy(sbuffer.data(), buffer.data(), allReaded);
					memcpy(buffer.data(), sbuffer.data(size_), allReaded);
					allReaded -= size_;
				} else {
					if (validatePayload(buffer.data(), dataSize))
						packetReceived(buffer.data(), dataSize);
					memcpy(sbuffer.data(), buffer.data(), allReaded);
					memcpy(buffer.data(), sbuffer.data(packetSize_hf), allReaded);
					allReaded -= packetSize_hf;
				}
			}
		}*/
		tmpbuf.append(readed, size_);
		ss = src_footer.size_s() + dataSize;
		while (tmpbuf.size_s() >= ss) {
			while (!validateFooter(src_footer.data(), tmpbuf.data(dataSize), src_footer.size_s())) {
				tmpbuf.pop_front();
				++missed;
				if (tmpbuf.size_s() < ss) return true;
			}
			while (!validatePayload(tmpbuf.data(), dataSize)) {
				tmpbuf.pop_front();
				++missed;
				if (tmpbuf.size_s() < ss) return true;
			}
			packetReceived(tmpbuf.data(), ss);
			tmpbuf.remove(0, ss);
		}
		break;
	case PIPacketExtractor::HeaderAndFooter:
		tmpbuf.append(readed, size_);
		ss = src_header.size_s() + src_footer.size_s();
		while (tmpbuf.size_s() >= ss) {
			if (!header_found) {
				if (tmpbuf.size_s() < ss) return true;
				while (!validateHeader(src_header.data(), tmpbuf.data(), src_header.size_s())) {
					tmpbuf.pop_front();
					++missed;
					if (tmpbuf.size_s() < ss) return true;
				}
				header_found = true;
				footerInd = src_header.size_s();
			} else {
				if (tmpbuf.size_s() < footerInd + src_footer.size_s()) return true;
				while (!validateFooter(src_footer.data(), tmpbuf.data(footerInd), src_footer.size_s())) {
					++footerInd;
					if (tmpbuf.size_s() < footerInd + src_footer.size_s()) return true;
				}
				//piCout << "footer found at" << footerInd;
				header_found = false;
				if (!validatePayload(tmpbuf.data(src_header.size_s()), footerInd - src_header.size_s())) {
					tmpbuf.pop_front();
					++missed;
					continue;
				}
				packetReceived(tmpbuf.data(), footerInd + src_footer.size_s());
				tmpbuf.remove(0, footerInd + src_footer.size_s());
				footerInd = src_header.size_s();
			}
		}
		break;
	case PIPacketExtractor::Size:
		tmpbuf.append(readed, size_);
		if (packetSize_ <= 0) {
			tmpbuf.clear();
			return true;
		}
		while (tmpbuf.size_s() >= packetSize_) {
			if (!validatePayload(tmpbuf.data(), packetSize_)) {
				tmpbuf.pop_front();
				++missed;
				missed_packets = missed / packetSize_;
				continue;
			}
			packetReceived(tmpbuf.data(), packetSize_);
			tmpbuf.remove(0, packetSize_);
		}
		break;
	case PIPacketExtractor::Timeout:
		memcpy(buffer.data(), readed, size_);
		trbuf = dev->readForTime(time_);
		memcpy(buffer.data(size_), trbuf.data(), trbuf.size());
		if (size_ + trbuf.size() > 0)
			packetReceived(buffer.data(), size_ + trbuf.size());
		break;
	};
	return true;
}


PIString PIPacketExtractor::constructFullPathDevice() const {
	return "";
}
