#include <iostream>
#include <fstream>
#include <ai2d.h>
#include <opencv2/opencv.hpp>

// Test image path and size
std::string image_path="test.jpg";

void setup() {
  // put your setup code here, to run once:
  // put your setup code here, to run once:
  cv::Mat input_image=cv::imread(image_path);
  size_t img_w=input_image.cols;
  size_t img_h=input_image.rows;
  // Affine matrix (scale 0.5 and translate by 100)
  std::vector<float> affine_matrix = {0.5,0.0,100.0,
                                      0.0,0.5,100.0};
  size_t out_w=img_w/2;
  size_t out_h=img_h/2;

  // Create input tensor from image data
  dims_t input_shape{1,img_h,img_w,3};
  runtime_tensor input_tensor = host_runtime_tensor::create(
      typecode_t::dt_uint8,
      input_shape,
      { (gsl::byte *)input_image.data, input_shape[0]*input_shape[1]*input_shape[2]*input_shape[3]},
      true,
      hrt::pool_shared
  ).expect("cannot create input tensor");
  hrt::sync(input_tensor, sync_op_t::sync_write_back, true).unwrap();

  /************* Affine Transform Sample *************/
  AI2D ai2d_affine=AI2D();
  ai2d_affine.set_ai2d_dtype(ai2d_format::RGB_packed, ai2d_format::RGB_packed,
                             typecode_t::dt_uint8, typecode_t::dt_uint8);
  ai2d_affine.set_affine(ai2d_interp_method::cv2_bilinear, 0, 0, 127, 1, affine_matrix);
  dims_t affine_input_shape{1,img_h,img_w,3};
  dims_t affine_output_shape{1,out_h,out_w,3};
  ai2d_affine.build(affine_input_shape,affine_output_shape);
  runtime_tensor ai2d_affine_tensor = host_runtime_tensor::create(typecode_t::dt_uint8, affine_output_shape, hrt::pool_shared).expect("cannot create input tensor");
  ai2d_affine.run(input_tensor,ai2d_affine_tensor);

  // Save affine result
  auto affine_input_buf = ai2d_affine_tensor.impl()->to_host().unwrap()->buffer().as_host().unwrap().map(map_access_::map_write).unwrap().buffer();
  char* affine_output_data=reinterpret_cast<char *>(affine_input_buf.data());
  cv::Mat affine_out_img(out_h,out_w, CV_8UC3, affine_output_data);
  cv::imwrite("affine_output.jpg", affine_out_img);
  /**************************************************/
}

void loop() {
  // put your main code here, to run repeatedly:

}
