Added code base.
[weightgraph] / weightgraph / weightstatsview.cpp
diff --git a/weightgraph/weightstatsview.cpp b/weightgraph/weightstatsview.cpp
new file mode 100644 (file)
index 0000000..65e4f0f
--- /dev/null
@@ -0,0 +1,77 @@
+#include "weightstatsview.h"
+#include "settings.h"
+#include <QVBoxLayout>
+#include <QGroupBox>
+
+#include <QDebug>
+
+WeightStatsView::WeightStatsView(WeightDataModel *wdm, QWidget *parent) :
+  QWidget(parent), wdm(wdm)
+{
+  connect(wdm, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
+          this, SLOT(updateStats()));
+  connect(wdm, SIGNAL(rowsInserted(const QModelIndex&,int,int)),
+          this, SLOT(updateStats()));
+  connect(wdm, SIGNAL(rowsRemoved(const QModelIndex&,int,int)),
+          this, SLOT(updateStats()));
+  connect(Settings::self(), SIGNAL(settingChanged()),
+          this, SLOT(updateStats()));
+
+  QVBoxLayout *lo = new QVBoxLayout(this);
+
+  last = new QLabel(this);
+  lo->addWidget(last);
+
+  change = new QLabel(this);
+  lo->addWidget(change);
+
+  updateStats();
+}
+
+QString dateString(QDate date)
+{
+  int days = date.daysTo(QDate::currentDate());
+  if (days < 0)
+    return date.toString(Qt::ISODate);
+  else if (days == 0)
+    return "Today";
+  else if (days == 1)
+    return "Yesterday";
+  else if (days < 7)
+    return date.toString("dddd");
+  else
+    return date.toString(Qt::ISODate);
+}
+
+QString dateIntervalString(int days)
+{
+  if (days < 30)
+    return QString("%1 days").arg(days);
+  else if (days < 360)
+    return QString("%1m %2d").arg(days/30).arg(days%30);
+  else if (days < 365)
+    return QString("1y 0m");
+  else
+    return QString("%1y %2m").arg(days/365).arg((days%365)/30);
+}
+
+void WeightStatsView::updateStats()
+{
+  if (wdm->size() == 0) {
+    last->setText("Last: No data");
+    change->setText("Change: No data");
+    return;
+  }
+  QString unit = Settings::weightUnit();
+  const DW &f = wdm->getWeights().first();
+  const DW &l = wdm->getWeights().last();
+  last->setText(tr("Last: %1 %2\n     (%3)")
+                .arg(l.weight,0,'f',1)
+                .arg(unit)
+                .arg(dateString(l.date)));
+  change->setText(tr("Change: %1 %2\n"
+                     "     (in %3)")
+                  .arg(l.weight-f.weight,0,'f',1)
+                  .arg(unit)
+                  .arg(dateIntervalString(f.date.daysTo(l.date))));
+}