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

#include "VentilatorHysteresisWidget.h"
#include "ui_VentilatorHysteresis.h"

#include "cdm/PhysiologyEngine.h"
#include "cdm/properties/SEScalarVolume.h"
#include "cdm/system/equipment/mechanical_ventilator/SEMechanicalVentilator.h"
#include "cdm/properties/SEScalarPressure.h"
#include "cdm/properties/SEScalarVolumePerTime.h"

#include "qwt.h"


struct QVentilatorHysteresisWidget::Private : public Ui::VentilatorHysteresis
{
  Private(QVentilatorHysteresisWidget* parent) : parent(parent) {
    setupUi(parent);

    {
        auto& plot = plot_0->GetPlot();
        plot.setAxisTitle(QwtPlot::yLeft, "Volume(mL)");
        plot.setAxisTitle(QwtPlot::xBottom, "Pressure(cmH20)");
        plot_0->SetAspectRatio(8.0);
        plot_0->SetMaxPoints(750);
    }

    {
        auto& plot = plot_1->GetPlot();
        plot.setAxisTitle(QwtPlot::yLeft, "Flow(L/min)");
        plot.setAxisTitle(QwtPlot::xBottom, "Volume(mL)");
        plot_1->SetAspectRatio(1.0/8.0);
        plot_1->SetMaxPoints(750);
    }
  }

  QVentilatorHysteresisWidget* parent;
};

QVentilatorHysteresisWidget::QVentilatorHysteresisWidget(QWidget* parent, Qt::WindowFlags flags) :
  QWidget(parent, flags),
  d(new Private(this))
{

}

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

void QVentilatorHysteresisWidget::AtSteadyState(PhysiologyEngine& pulse)
{
}

void QVentilatorHysteresisWidget::AtSteadyStateUpdateUI()
{
}

void QVentilatorHysteresisWidget::ProcessPhysiology(PhysiologyEngine& pulse)
{
  auto ventilator = pulse.GetMechanicalVentilator();

  double volume = ventilator->GetTotalLungVolume(VolumeUnit::mL);

  d->plot_0->Append(volume, ventilator->GetAirwayPressure(PressureUnit::cmH2O));
  d->plot_1->Append(ventilator->GetInspiratoryFlow(VolumePerTimeUnit::L_Per_min), volume);
}

void QVentilatorHysteresisWidget::PhysiologyUpdateUI(const std::vector<SEAction const*>& actions)
{
    if (d->plot_0->isVisible())
    {
        d->plot_0->UpdateUI();
        d->plot_1->UpdateUI();
    }
}

void QVentilatorHysteresisWidget::EngineErrorUI()
{
}
