#include "pylonwrapper.h"

PylonWrapper::PylonWrapper():
  valid(false) {
  Pylon::PylonInitialize();
  camera = new Pylon::CInstantCamera();
}

PylonWrapper::~PylonWrapper() {
  Pylon::PylonTerminate();
}

void PylonWrapper::terminate() {
  try {
    //Pylon::PylonTerminate();
  } catch (const Pylon::GenericException &e) {
    std::cerr << e.GetDescription() << std::endl;
  }
}

bool PylonWrapper::isOpen() {
  return valid;
}

ImageSettings PylonWrapper::getImageSettings() {
  ImageSettings settings;
  if (valid) {
    Pylon::CIntegerParameter width( camera->GetNodeMap(), "Width");
    Pylon::CIntegerParameter height( camera->GetNodeMap(), "Height");
    Pylon::CEnumParameter pixelFormat( camera->GetNodeMap(), "PixelFormat");
    settings.width = width.GetValue();
    settings.height = height.GetValue();
  }
  return settings;
}

bool PylonWrapper::grabFrame(MyImage &img) {
  Pylon::CGrabResultPtr frame;
  if (valid) {
    camera->StartGrabbing();
    camera->RetrieveResult( 5000, frame, Pylon::TimeoutHandling_ThrowException);
    camera->StopGrabbing();
  }
  img.setFrame(frame);
  return frame.IsValid();
}

bool PylonWrapper::openCamera(std::string &message) {
  try {
    camera->Attach(Pylon::CTlFactory::GetInstance().CreateFirstDevice());
    camera->Open();
    valid = true;
    message = "Successfully opened camera!";
  } catch (const Pylon::GenericException &e) {
    message = e.GetDescription();
    std::cerr << "An exception occurred." << std::endl << e.GetDescription() << std::endl;
    valid = false;
  }
  return valid;
}

void PylonWrapper::closeCamera() {
  if (camera->IsOpen()) {
      try {
        camera->Close();
        valid = false;
      } catch (const Pylon::GenericException &e) {
        std::cerr << "An exception occurred." << std::endl << e.GetDescription() << std::endl;
      }
    }
}