/*
 * Copyright 2022 KylinSoft Co., Ltd.
 *
 * 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 2 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 thi1s program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "memorymonitor.h"
#include <QProcess>
#include <QDebug>

MemoryMonitor::MemoryMonitor(QObject *parent) : QObject(parent)
{
    m_timer = new QTimer(this);
    connect(m_timer,SIGNAL(timeout()),this,SLOT(getSystemInfo()));
    startTime(30000);
}
void MemoryMonitor::getSystemInfo()
{
    QProcess process;
    process.start("cat /proc/meminfo");
    bool processret = process.waitForFinished();
    if (!processret) {
        return;
    }
    while (!process.atEnd()) {
        QString str = process.readLine();
        if (str.startsWith("MemTotal")) {
            str.replace("\n","");
            str.replace(QRegExp("( ){1,}")," ");
            auto lst = str.split(" ");
            if (lst.size() > 2) {
                m_memtotal = lst[1].toLong();
            }
        }
        if (str.startsWith("MemAvailable")) {
            str.replace("\n","");
            str.replace(QRegExp("( ){1,}")," ");
            auto lst = str.split(" ");
            if(lst.size() > 2)
                m_memavailable = lst[1].toLong();
        }
    }
    if ((m_memtotal != 0) && (m_memavailable != 0)) {
        m_available = m_memavailable / m_memtotal;
        if(m_available<0.1) {
            qDebug() << "Available memory less than %10" << endl;
            emit lowMemoryWaining();
        }
    }
}
void MemoryMonitor::startTime(int time)
{
    m_timer->start(time);
}

