#include "myimage.h"
#include <chrono>
#include "mylogger.h"

MyImage::MyImage(uint32_t width, uint32_t height): img_width(width), img_height(height)
{
  buffer = new char[width * height];
}

MyImage::MyImage(Pylon::CGrabResultPtr ptr) {
  setFrame(ptr);
}

MyImage::~MyImage() {
  delete[] buffer;
}

bool MyImage::setFrame(Pylon::CGrabResultPtr ptr) {
  qDebug() << "Setting frame from pointer";
  bool valid = ptr.IsValid() && ptr->GetWidth() <= max_width && ptr->GetHeight() <= max_height;
  if (valid) {
      img_index = ptr->GetID();
      img_width = ptr->GetWidth();
      img_height = ptr->GetHeight();
      memcpy(buffer, ptr->GetBuffer(), ptr->GetImageSize());
      auto t = std::chrono::system_clock::now();
      img_timestamp = std::chrono::system_clock::to_time_t(t);
    }
  return valid;
}

bool MyImage::setFrame( Pylon::CPylonImage &img) {
  qDebug() << "Setting frame from Pylon image (" << img.GetWidth() << "x" << img.GetHeight() << ")";
  bool valid = img.IsValid() && img.GetWidth() <= max_width && img.GetHeight() <= max_height;
  if (valid) {
      img_width = img.GetWidth();
      img_height = img.GetHeight();
      memcpy(buffer, img.GetBuffer(), img.GetImageSize());
      auto t = std::chrono::system_clock::now();
      img_timestamp = std::chrono::system_clock::to_time_t(t);
    }
  return valid;
}

int MyImage::width() {
  return static_cast<int>(img_width);
}

int MyImage::height() {
  return static_cast<int>(img_height);
}

int MyImage::size() {
  return static_cast<int>(img_width * img_height);
}

int64_t MyImage::index() {
  return img_index;
}

void *MyImage::data() {
  return buffer;
}

time_t MyImage::timestamp() {
  return img_timestamp;
}