#include "AmpereControllingHeater.hpp"
#include "schneide_base/CSVReader.hpp"
#include "schneide_base/Logger.hpp"

using namespace vera;
using namespace schneide;

AmpereControllingHeater::AmpereControllingHeater(std::unique_ptr<AmpereControl> Control, HeaterConfiguration const& config)
: AmpereControllingHeater(std::move(Control), config.rampFile(), config.preHeatTime())
{
}

AmpereControllingHeater::AmpereControllingHeater(std::unique_ptr<AmpereControl> Control, std::string const& rampFile, Duration preHeat)
: mControl(std::move(Control)), mPreHeat(preHeat)
{
  auto parsed = CSVReader::parseFile(rampFile);
  for (auto const& line : parsed)
  {
    auto ampere = line.at(0).asDouble();
    auto time = Duration(line.at(1).asDouble());

    mAmpereAndHoldTime.emplace_back(ampere, time);
  }
}

void AmpereControllingHeater::setAmpere(Interactor& interactor, double ampere)
{
  Logger::get()->info("Setting {0} ampere", ampere);
  mControl->setAmpere(interactor, ampere);
}

void AmpereControllingHeater::prepare(Interactor& interactor)
{
  mControl->start(interactor);

  if (mAmpereAndHoldTime.empty())
    return;

  // Use the last entry in the ramp for pre-heating "temperature"
  setAmpere(interactor, mAmpereAndHoldTime.back().first);
  interactor.wait(mPreHeat);
}

void AmpereControllingHeater::shutdown(Interactor& interactor)
{
  mControl->stop(interactor);
}

void AmpereControllingHeater::burnClean(Interactor& interactor)
{
  for (auto const& Entry : mAmpereAndHoldTime)
  {
    setAmpere(interactor, Entry.first);

    // Wait for the specified amount of time
    interactor.wait(Entry.second);
  }
}
