Added code base.
[weightgraph] / weightgraph / weightstatsview.cpp
1 #include "weightstatsview.h"
2 #include "settings.h"
3 #include <QVBoxLayout>
4 #include <QGroupBox>
5
6 #include <QDebug>
7
8 WeightStatsView::WeightStatsView(WeightDataModel *wdm, QWidget *parent) :
9   QWidget(parent), wdm(wdm)
10 {
11   connect(wdm, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
12           this, SLOT(updateStats()));
13   connect(wdm, SIGNAL(rowsInserted(const QModelIndex&,int,int)),
14           this, SLOT(updateStats()));
15   connect(wdm, SIGNAL(rowsRemoved(const QModelIndex&,int,int)),
16           this, SLOT(updateStats()));
17   connect(Settings::self(), SIGNAL(settingChanged()),
18           this, SLOT(updateStats()));
19
20   QVBoxLayout *lo = new QVBoxLayout(this);
21
22   last = new QLabel(this);
23   lo->addWidget(last);
24
25   change = new QLabel(this);
26   lo->addWidget(change);
27
28   updateStats();
29 }
30
31 QString dateString(QDate date)
32 {
33   int days = date.daysTo(QDate::currentDate());
34   if (days < 0)
35     return date.toString(Qt::ISODate);
36   else if (days == 0)
37     return "Today";
38   else if (days == 1)
39     return "Yesterday";
40   else if (days < 7)
41     return date.toString("dddd");
42   else
43     return date.toString(Qt::ISODate);
44 }
45
46 QString dateIntervalString(int days)
47 {
48   if (days < 30)
49     return QString("%1 days").arg(days);
50   else if (days < 360)
51     return QString("%1m %2d").arg(days/30).arg(days%30);
52   else if (days < 365)
53     return QString("1y 0m");
54   else
55     return QString("%1y %2m").arg(days/365).arg((days%365)/30);
56 }
57
58 void WeightStatsView::updateStats()
59 {
60   if (wdm->size() == 0) {
61     last->setText("Last: No data");
62     change->setText("Change: No data");
63     return;
64   }
65   QString unit = Settings::weightUnit();
66   const DW &f = wdm->getWeights().first();
67   const DW &l = wdm->getWeights().last();
68   last->setText(tr("Last: %1 %2\n     (%3)")
69                 .arg(l.weight,0,'f',1)
70                 .arg(unit)
71                 .arg(dateString(l.date)));
72   change->setText(tr("Change: %1 %2\n"
73                      "     (in %3)")
74                   .arg(l.weight-f.weight,0,'f',1)
75                   .arg(unit)
76                   .arg(dateIntervalString(f.date.daysTo(l.date))));
77 }