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

  /************* Resize Sample *************/
  AI2D ai2d_resize=AI2D();
  // Configure dtype: input/output are RGB packed format, uint8
  ai2d_resize.set_ai2d_dtype(ai2d_format::RGB_packed, ai2d_format::RGB_packed,
                             typecode_t::dt_uint8, typecode_t::dt_uint8);
  // Set resize interpolation method
  ai2d_resize.set_resize(ai2d_interp_method::tf_bilinear, ai2d_interp_mode::half_pixel);
  dims_t resize_input_shape{1,img_h,img_w,3};
  dims_t resize_output_shape{1,out_h,out_w,3};
  ai2d_resize.build(resize_input_shape,resize_output_shape);
  runtime_tensor ai2d_resize_tensor = host_runtime_tensor::create(typecode_t::dt_uint8, resize_output_shape, hrt::pool_shared).expect("cannot create input tensor");
  ai2d_resize.run(input_tensor,ai2d_resize_tensor);

  // Save resize result
  auto resize_input_buf = ai2d_resize_tensor.impl()->to_host().unwrap()->buffer().as_host().unwrap().map(map_access_::map_write).unwrap().buffer();
  char* resize_output_data=reinterpret_cast<char *>(resize_input_buf.data());
  cv::Mat resize_out_img(out_h,out_w, CV_8UC3, resize_output_data);
  cv::imwrite("resize_output.jpg", resize_out_img);
  /****************************************/
}

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

}
