/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQMemoryWidget.h"

#include <QtGlobal>
#include <QDebug>
#include <QTextStream>

#include <stdlib.h>
#include <unistd.h>
//#include <sys/time.h>
//#include <sys/resource.h>

MvQMemoryWidget::MvQMemoryWidget(QWidget* parent) :
    QLabel(parent)
{
    //memInfoFile_= new QFile("/proc/meminfo");
    pid_ = getpid();
}

void MvQMemoryWidget::slotRefresh()
{
    //struct rusage usage;

    //getrusage(RUSAGE_SELF,&usage);

    //maxrss_=usage.ru_maxrss;

    QFile memInfoFile("/proc/meminfo");

    if (memInfoFile.open(QIODevice::ReadOnly | QIODevice::Text) == false) {
        return;
    }

    int findItems = 0;

    QTextStream in(&memInfoFile);
    QString line = in.readLine();
    while (!line.isNull() && findItems < 2) {
        if (parseMemInfoLine("MemTotal", line, memTotal_, memTotalUnit_)) {
            findItems++;
        }
        else if (parseMemInfoLine("MemFree", line, memFree_, memFreeUnit_)) {
            findItems++;
        }
        line = in.readLine();
    }

    memInfoFile.close();


    QFile procFile("/proc/" + QString::number(pid_) + "/statm");

    if (procFile.open(QIODevice::ReadOnly | QIODevice::Text) == false) {
        return;
    }

    QTextStream inProc(&procFile);
    QStringList lst = inProc.readLine().split(" ",
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
                                              Qt::SkipEmptyParts);
#else
                                              QString::SkipEmptyParts);
#endif

    maxrss_ = lst[1].toLong();

    procFile.close();


    QString txt = QString::number(maxrss_) + " " + QString::number(memTotal_) + " " +
                  QString::number(memFree_);


    setText(txt);
}

bool MvQMemoryWidget::parseMemInfoLine(QString key, QString line, long& value, QString& unit)
{
    QStringList lst = line.split(":");
    if (lst.count() == 2 && lst[0].compare(key) == 0) {
        QStringList nLst = lst[1].simplified().split(" ");
        if (nLst.count() == 2) {
            value = nLst[0].toLong();
            unit  = nLst[1];
            return true;
        }
    }
    return false;
}

long MvQMemoryWidget::memTotal()
{
    return memTotal_;
}

long MvQMemoryWidget::memFree()
{
    return memFree_;
}

long MvQMemoryWidget::maxrss()
{
    return maxrss_;
}


#if 0
struct rusage {
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    long   ru_maxrss;        /* maximum resident set size */
    long   ru_ixrss;         /* integral shared memory size */
    long   ru_idrss;         /* integral unshared data size */
    long   ru_isrss;         /* integral unshared stack size */
    long   ru_minflt;        /* page reclaims */
    long   ru_majflt;        /* page faults */
    long   ru_nswap;         /* swaps */
    long   ru_inblock;       /* block input operations */
    long   ru_oublock;       /* block output operations */
    long   ru_msgsnd;        /* messages sent */
    long   ru_msgrcv;        /* messages received */
    long   ru_nsignals;      /* signals received */
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */
};

#endif
