#include "ComStatistics.h"
#include <QMutex>
#include <QDateTime>
#include <QFile>
#include <QDir>
#include <QTextStream>

ComStatistics::ComStatistics(QString sensor_name):
tag_name(sensor_name)
{
    request_count = 0;
    crcerror_count = 0;
    timeout_count = 0;

    max_recvtime = 0;
    min_recvtime = 0;
    total_recvtime = 0;
}

void ComStatistics::ReQuestCount_increase()
{
    request_count++;
}


void ComStatistics::CrcErrorCount_increase()
{
    crcerror_count++;
}

void ComStatistics::TimeoutCount_increase()
{
    timeout_count++;
}

void ComStatistics::Update_Recvtime(int ms)
{
    if(ms > max_recvtime){
       max_recvtime = ms;
    }

    if(ms < min_recvtime){
       min_recvtime = ms;
    }

    total_recvtime += ms;

}

void ComStatistics::Save2File(QString filepath)
{
    static QMutex mutex;
    mutex.lock();
    QString time=QDateTime::currentDateTime().toString(QString("[ yyyy-MM-dd HH:mm:ss:zzz ]"));
    QString mmsg;
    mmsg = time + "["+ tag_name +"]:";
    mmsg += "\r\n";

    QString requestString;
    requestString = "\t ReQuestCount:" + QString::number(request_count) + "\r\n";

    QString crcString;
    crcString = "\t CrcErrorCount:" + QString::number(crcerror_count) + "\r\n";

    QString timeoutString;
    timeoutString = "\t TimeoutCount:" + QString::number(timeout_count) + "\r\n";

    QString maxtimeString;
    maxtimeString = "\t max_Recvtime:" + QString::number(max_recvtime) + " ms\r\n";

    QString mintimeString;
    mintimeString = "\t min_Recvtime:" + QString::number(min_recvtime) + " ms\r\n";

    QString averagetimeString;
    averagetimeString = "\t Averagetime:" + QString::number(total_recvtime/request_count) + " ms\r\n";

    QFile file(filepath);
    file.open(QIODevice::ReadWrite | QIODevice::Append);

    QTextStream stream(&file);

    stream << mmsg;
    stream << requestString;
    stream << crcString;
    stream << timeoutString;
    stream << maxtimeString;
    stream << mintimeString;
    stream << averagetimeString;
    stream << "\r\n";

    file.flush();
    file.close();
    mutex.unlock();
}
