#include "dlg_videobitrates.h"
#include <QTimer>
#include "log2ui.h"

///
#define qDebug_Mod qDebug() << Utf8Str("---- Video ")
Dlg_VideoBitrates::Dlg_VideoBitrates(IGetMediaStats* api, QWidget *parent)
: QDialog(parent), api_(api)
{
	ui.setupUi(this);
	initBitratesGraph();
}

Dlg_VideoBitrates::~Dlg_VideoBitrates()
{
}

void Dlg_VideoBitrates::setvbName(const QString& name) {
	ui.vbgraph->graph(0)->setName(name+" KBps");
}
void Dlg_VideoBitrates::setTargetBitrate(int bitrate) {
	targetbitrate_ = bitrate;
	ui.vbgraph->yAxis->setRange(0, targetbitrate_);
}
void Dlg_VideoBitrates::start() {
	timer_->start();
}
void Dlg_VideoBitrates::stop() {
	timer_->stop();
}
int  Dlg_VideoBitrates::s_xAxis_minute = 20 * 60;
void Dlg_VideoBitrates::initBitratesGraph() {
	ui.vbgraph->addGraph();
	ui.vbgraph->graph(0)->setPen(QPen(Qt::blue));
	ui.vbgraph->graph(0)->setName(Utf8Str("速率KB"));
	ui.vbgraph->addGraph();
	ui.vbgraph->graph(1)->setPen(QPen(Qt::red));
	ui.vbgraph->graph(1)->setName(Utf8Str("丢包率"));
	//
	ui.vbgraph->xAxis->setTickLabelSide(QCPAxis::lsInside);
	ui.vbgraph->xAxis->setTickLabelType(QCPAxis::ltDateTime);
	ui.vbgraph->xAxis->setDateTimeFormat("mm:ss");
	ui.vbgraph->xAxis->setAutoTickStep(false);
	ui.vbgraph->xAxis->setTickStep(60 * 5);
	ui.vbgraph->axisRect()->setupFullAxesBox();
	//
	ui.vbgraph->yAxis->setTickLabelType(QCPAxis::ltNumber);
    ui.vbgraph->yAxis->setNumberFormat("gb");
	ui.vbgraph->yAxis->setNumberPrecision(0);
	ui.vbgraph->yAxis->setRange(0, 200);
	ui.vbgraph->legend->setVisible(true);
	//
	timer_ = new QTimer(this);
	timer_->setInterval(5000);
	connect(timer_, SIGNAL(timeout()), this, SLOT(onTimerOut()));
}
void Dlg_VideoBitrates::onTimerOut() {
	if (NULL == api_) {
		return;
	}
	double key = QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000.0;

	const rtc::MediaStats& stats = api_->getMediaStats();
	int bitrate = stats.bps_sent / (1024 * 8);
	int lostpec = stats.lostpercent * targetbitrate_ / 100;
	if (bitrate > (targetbitrate_ *1.2) || (bitrate < targetbitrate_/1.5)){
		qDebug_Mod << Utf8Str(" ") << QDateTime::currentDateTime().toString("hh:mm:ss") << Utf8Str(" 速率-") << bitrate
			<< Utf8Str(",丢包-") << stats.lostpercent << Utf8Str(",帧率-") << stats.frame_rate;
	}
	ui.vbgraph->graph(0)->addData(key, bitrate);
	ui.vbgraph->graph(1)->addData(key, lostpec);

	//删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
	//才能起到想要的效果，可以调整这两个值，观察显示的效果。
	ui.vbgraph->graph(0)->removeDataBefore(key - s_xAxis_minute);
	ui.vbgraph->graph(1)->removeDataBefore(key - s_xAxis_minute);
	//ui.vbgraph->graph(0)->rescaleValueAxis();
	//这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
	//就把8调整为比较大到值，比如要显示60秒，那就改成60。
	//这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
	ui.vbgraph->xAxis->setRange(key + 0.25, s_xAxis_minute, Qt::AlignRight);//设定x轴的范围
	ui.vbgraph->replot();
}
