/*
    PIP - Platform Independent Primitives
   Speed and quality in/out diagnostics
    Copyright (C) 2016  Ivan Pelipenko peri4ko@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU 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 General Public License for more details.

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

#include "pidiagnostics.h"


/** \class PIDiagnostics
 * \brief Connection quality diagnostics
 * \details
 * \section PIDiagnostics_sec0 Synopsis
 * This class provide abstract connection quality diagnostics and
 * counting. You should create instance of %PIDiagnostics and on
 * packet receive call function \a received(), on packet send call
 * function \a sended(). %PIDiagnostics calculates correct, wrong
 * and sended counters, packets per second, bytes per seconds,
 * immediate and integral receive frequencies and receive/send speeds
 * in human readable representation. There statistics are calculates
 * one time per period, by default 1 second. To calculate them you
 * should start %PIDiagnostics with function \a start() or pass \b true
 * to constructor.
 * */


PIDiagnostics::PIDiagnostics(bool start_): PITimer(PITimer::Pool) {
	disconn_ = 0.;
	setInterval(100);
	reset();
	setDisconnectTimeout(3.);
	changeDisconnectTimeout(3.);
	if (start_) start(100);
}


void PIDiagnostics::reset() {
	lock();
	qual = PIDiagnostics::Unknown;
	speedRecv = speedSend = PIString::readableSize(0) + "/s";
	immediate_freq = integral_freq = 0.f;
	count_wrong = count_recv = count_send = bytes_wrong = bytes_recv = bytes_send = 0;
	packets_recv_sec = packets_send_sec = bytes_recv_sec = bytes_send_sec = 0;
	if (disconn_ != 0.) {
		int hist_size = history_rec.size();
		history_rec.clear();
		history_send.clear();
		history_rec.resize(hist_size);
		history_send.resize(hist_size);
	}
	unlock();
}


void PIDiagnostics::received(int size, bool correct) {
	lock();
	Entry & e(history_rec.front());
	if (correct) {
		e.cnt_ok++;
		e.bytes_ok += size;
		count_recv++;
		bytes_recv += size;
	} else {
		e.cnt_fail++;
		e.bytes_fail += size;
		count_wrong++;
		bytes_wrong += size;
	}
	e.empty = false;
	unlock();
}


void PIDiagnostics::sended(int size) {
	lock();
	Entry & e(history_send.front());
	e.cnt_ok++;
	e.bytes_ok += size;
	count_send++;
	bytes_send += size;
	e.empty = false;
	unlock();
}


void PIDiagnostics::tick(void * , int ) {
	lock();
	int tcnt_recv = 0;
	int tcnt_send = 0;
	Entry send = calcHistory(history_send, tcnt_send);
	Entry recv = calcHistory(history_rec, tcnt_recv);
	float itr = disconn_ * (float(tcnt_recv) / history_rec.size());
	float its = disconn_ * (float(tcnt_send) / history_send.size());
	float hz = interval() / 1000.f;
	integral_freq = recv.cnt_ok / itr;
	packets_recv_sec = ullong(float(recv.cnt_ok) / itr);
	packets_send_sec = ullong(float(send.cnt_ok) / its);
	bytes_recv_sec = ullong(double(recv.bytes_ok) / itr);
	bytes_send_sec = ullong(double(send.bytes_ok) / its);
	immediate_freq = double(history_rec.front().cnt_ok) / hz;
//	piCoutObj << "tick" << recv.cnt_ok << send.cnt_ok;
//	speedRecv = PIString::readableSize(ullong(double(history_rec.front().bytes_ok) / hz)) + "/s";
//	speedSend = PIString::readableSize(ullong(double(history_send.front().bytes_ok) / hz)) + "/s";
	speedRecv = PIString::readableSize(bytes_recv_sec) + "/s";
	speedSend = PIString::readableSize(bytes_send_sec) + "/s";
	int arc = recv.cnt_ok + recv.cnt_fail;
	float good_percents = 0.f;
	if (arc > 0) good_percents = (float)recv.cnt_ok / arc * 100.f;
	PIDiagnostics::Quality diag;
	if (tcnt_recv == 0) {
		diag = PIDiagnostics::Unknown;
	} else {
		if (good_percents == 0.f) diag = PIDiagnostics::Failure;
		else if (good_percents <= 20.f) diag = PIDiagnostics::Bad;
		else if (good_percents > 20.f && good_percents <= 80.f) diag = PIDiagnostics::Average;
		else diag = PIDiagnostics::Good;

	}
	if ((tcnt_send + tcnt_recv) != 0) {
//		piCoutObj << tcnt_recv << tcnt_send;
		history_rec.dequeue();
		history_send.dequeue();
		Entry e;
		e.empty = false;
		history_rec.enqueue(e);
		history_send.enqueue(e);
	}
	if (diag != qual) {
		qualityChanged(diag, qual);
		qual = diag;
	}
	unlock();
}


PIDiagnostics::Entry PIDiagnostics::calcHistory(PIQueue<Entry> & hist, int & cnt) {
	Entry e;
	cnt = 0;
	for (int i = 0; i < hist.size_s(); ++i) {
		e.bytes_ok += hist[i].bytes_ok;
		e.bytes_fail += hist[i].bytes_fail;
		e.cnt_ok += hist[i].cnt_ok;
		e.cnt_fail += hist[i].cnt_fail;
		if (!hist[i].empty) cnt++;
	}
	e.empty = false;
//	piCoutObj << hist.size() << cnt;
	return e;
}


void PIDiagnostics::propertyChanged(const PIString &) {
	float disct = property("disconnectTimeout").toFloat();
	changeDisconnectTimeout(disct);
}


void PIDiagnostics::changeDisconnectTimeout(float disct) {
	lock();
	disconn_ = piMaxf(disct, interval() / 1000.f);
	if (interval() > 0) {
		int hist_size = piMaxi(int(disconn_ * 1000. / interval()), 1);
		//piCoutObj << hist_size << interval();
		history_rec.resize(hist_size);
		history_send.resize(hist_size);
	} else {
		history_rec.resize(1);
		history_send.resize(1);
	}
	//piCoutObj << hist_size << disconn_ << interval();
	unlock();
}

