/*
 * Copyright 2022-2023 Advanced Micro Devices Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "./retinanet_imp.hpp"

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <vitis/ai/env_config.hpp>
#include <vitis/ai/profiling.hpp>

using namespace std;

DEF_ENV_PARAM(ENABLE_RetinaNet_DEBUG, "0");

namespace vitis {
namespace ai {

RetinaNetImp::RetinaNetImp(const std::string& model_name, bool need_preprocess) :
    RetinaNet(model_name, need_preprocess),
    processor_{vitis::ai::RetinaNetPostProcess::create(
        configurable_dpu_task_->getInputTensor()[0],
        configurable_dpu_task_->getOutputTensor()[0],
        configurable_dpu_task_->getConfig())} {

}

RetinaNetImp::RetinaNetImp(const std::string& model_name, xir::Attrs* attrs, bool need_preprocess) :
    RetinaNet(model_name, attrs, need_preprocess),
    processor_{vitis::ai::RetinaNetPostProcess::create(
        configurable_dpu_task_->getInputTensor()[0],
        configurable_dpu_task_->getOutputTensor()[0],
        configurable_dpu_task_->getConfig())} {

}

RetinaNetImp::~RetinaNetImp() {
}

std::vector<RetinaNetBoundingBox> RetinaNetImp::run(const cv::Mat& input_img) {
    cv::Mat img;
    auto size = cv::Size(getInputWidth(), getInputHeight());
    if (size != input_img.size()) {
        cv::resize(input_img, img, size, 0, 0, cv::INTER_LINEAR);
    } else {
        img = input_img;
    }
    configurable_dpu_task_->setInputImageRGB(img);

    __TIC__(RetinaNet_dpu)
    configurable_dpu_task_->run(0);
    __TOC__(RetinaNet_dpu)

    __TIC__(RetinaNet_post)
    auto ret = processor_->retinanet_post_process(1u);
     __TOC__(RetinaNet_post)
    return ret[0];
}

std::vector<std::vector<RetinaNetBoundingBox>> RetinaNetImp::run(const std::vector<cv::Mat>& input_img) {
  auto size = cv::Size(getInputWidth(), getInputHeight());
  auto batch_size = input_img.size();

  std::vector<cv::Mat> vimg(batch_size);

  for (auto i = 0ul; i < batch_size; i++) {
    if (size != input_img[i].size()) {
      cv::resize(input_img[i], vimg[i], size, 0, 0, cv::INTER_LINEAR);
    } else {
      vimg[i] = input_img[i];
    }
  }

  configurable_dpu_task_->setInputImageRGB(vimg);

  __TIC__(RetinaNet_dpu)
  configurable_dpu_task_->run(0);
  __TOC__(RetinaNet_dpu)

  __TIC__(RetinaNet_post)
  auto results = processor_->retinanet_post_process(input_img.size());
  __TOC__(RetinaNet_post)

  return results;
}

}  // namespace ai
}  // namespace vitis
