#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:
  cv::Mat input_image=cv::imread(image_path);
  size_t img_w=input_image.cols;
  size_t img_h=input_image.rows;
  size_t crop_x=0;
  size_t crop_y=0;
  size_t crop_w=img_w/2;
  size_t crop_h=img_h/2;
  size_t out_w=crop_w;
  size_t out_h=crop_h;

  // 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();

  /************* Cropping Sample *************/
  AI2D ai2d_crop=AI2D();
  ai2d_crop.set_ai2d_dtype(ai2d_format::RGB_packed, ai2d_format::RGB_packed,
                           typecode_t::dt_uint8, typecode_t::dt_uint8);
  // Crop region: start=(0,0), size=(out_w x out_h)
  ai2d_crop.set_crop(crop_x,crop_y,crop_w,crop_h);
  dims_t crop_input_shape{1,img_h,img_w,3};
  dims_t crop_output_shape{1,out_h,out_w,3};
  ai2d_crop.build(crop_input_shape,crop_output_shape);
  runtime_tensor ai2d_crop_tensor = host_runtime_tensor::create(typecode_t::dt_uint8, crop_output_shape, hrt::pool_shared).expect("cannot create input tensor");
  ai2d_crop.run(input_tensor,ai2d_crop_tensor);
  // Save crop result
  auto crop_input_buf = ai2d_crop_tensor.impl()->to_host().unwrap()->buffer().as_host().unwrap().map(map_access_::map_write).unwrap().buffer();
  char* crop_output_data=reinterpret_cast<char *>(crop_input_buf.data());
  cv::Mat crop_out_img(out_h,out_w, CV_8UC3, crop_output_data);
  cv::imwrite("crop_output.jpg", crop_out_img);
  /******************************************/
}

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

}
