/* Distributed under the Apache License, Version 2.0.
   See accompanying NOTICE file for details.*/

#include "NumberWidget.h"
#include "ui_NumberWidget.h"

#include "cdm/CommonDefs.h"
#include "cdm/engine/SEDataRequest.h"
#include "cdm/engine/SEDataRequestManager.h"
#include "cdm/engine/SEEngineTracker.h"
#include "pulse/engine/PulseEngine.h"

struct NumberWidget::Private : public Ui::NumberWidget
{
  int precision = 0;
  int factor = 1;
  double actualValue = 0.0;
  QString name;
  QString unit;

  SEDataRequest* request;
};

NumberWidget::NumberWidget(QFrame* parent) :
  QFrame(parent),
  d(new Private())
{
  d->setupUi(this);
}

NumberWidget::~NumberWidget()
{
  delete d;
}

void NumberWidget::setup(QString name, QString unit, int precision /*= 0*/)
{
  setName(name);
  setUnit(unit);
  setPrecision(precision);
}

QString NumberWidget::getName() const
{
  return d->name;
}

void NumberWidget::setName(QString name)
{
  d->name = name;
  d->label->setText(d->name + " " + d->unit);
}

QString NumberWidget::getUnit() const
{
  return d->unit;
}

void NumberWidget::setUnit(QString unit)
{
  d->unit = unit;
  d->label->setText(d->name + " " + d->unit);
}

double NumberWidget::getValue() const
{
  return d->actualValue;
}

void NumberWidget::setValue(double val)
{
  d->value->setText(QString::number( (std::round(val * d->factor)) / d->factor , 'f', d->precision));
  d->actualValue = val;
}

void NumberWidget::setPrecision(int val)
{
  d->precision = val;
  d->factor = 1;
  for (int i = 0; i < val; ++i)
  {
      d->factor *= 10;
  }
  setValue(d->actualValue);
}

int NumberWidget::getPrecision() const
{
  return d->precision;
}

void NumberWidget::processPhysiology(PhysiologyEngine& pulse)
{
  if (d->request != nullptr)
  {
    d->actualValue = pulse.GetEngineTracker()->GetValue(*(d->request));
  }
}

void NumberWidget::setDataRequest(SEDataRequest* request)
{
  d->request = request;
}

void NumberWidget::updateValue()
{
  setValue(d->actualValue);
}

void NumberWidget::setWithoutUpdate(double val)
{
  d->actualValue = val;
}
