Fixed a locale bug in stats view, improved edit window.
[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 static const char* wdays[] = {"Monday", "Tuesday", "Wednesday", "Thursday",
32                               "Friday", "Saturday", "Sunday"};
33 QString dateString(QDate date)
34 {
35   int days = date.daysTo(QDate::currentDate());
36   if (days < 0)
37     return date.toString(Qt::ISODate);
38   else if (days == 0)
39     return "Today";
40   else if (days == 1)
41     return "Yesterday";
42   else if (days < 7)
43     // return date.toString("dddd"); (Use this with l10n!)
44     // The following is used because the system locale might not be English
45     return wdays[date.dayOfWeek()-1];
46   else
47     return date.toString(Qt::ISODate);
48 }
49
50 QString dateIntervalString(int days)
51 {
52   if (days < 30)
53     return QString("%1 days").arg(days);
54   else if (days < 360)
55     return QString("%1m %2d").arg(days/30).arg(days%30);
56   else if (days < 365)
57     return QString("1y 0m");
58   else
59     return QString("%1y %2m").arg(days/365).arg((days%365)/30);
60 }
61
62 void WeightStatsView::updateStats()
63 {
64   if (wdm->size() == 0) {
65     last->setText("Last: No data");
66     change->setText("Change: No data");
67     return;
68   }
69   QString unit = Settings::weightUnit();
70   const DW &f = wdm->getWeights().first();
71   const DW &l = wdm->getWeights().last();
72   last->setText(tr("Last: %1 %2\n     (%3)")
73                 .arg(l.weight,0,'f',1)
74                 .arg(unit)
75                 .arg(dateString(l.date)));
76   change->setText(tr("Change: %1 %2\n"
77                      "     (in %3)")
78                   .arg(l.weight-f.weight,0,'f',1)
79                   .arg(unit)
80                   .arg(dateIntervalString(f.date.daysTo(l.date))));
81 }