#include "RwAlgorithm.h"
#include "Core/Logger.h"
#include <ds_pedestrian_mot_hisi.h>
#include <filesystem>
#include <opencv2/opencv.hpp>

bool Algorithm::initialize() {
    using namespace std::chrono;
    if (m_firstTime == system_clock::time_point{}) {
        m_firstTime = system_clock::now();
    }
    if (duration_cast<seconds>(system_clock::now() - m_firstTime) < seconds(10)) {
        return false;
    }

    constexpr auto licensePath = "/kdata/net.lic";
    bool licenseExisted = std::filesystem::exists(licensePath);
    if (licenseExisted && std::filesystem::file_size(licensePath) <= 0) {
        LOG(warning) << "license[" << licensePath << "] content is empty, remove it.";
        std::filesystem::remove(licensePath);
        licenseExisted = false;
    }
    ds_pedestrian_hisi_set_lic_path("/kdata");
    int status =
        ds_pedestrian_hisi_init(&m_handle, "/system/models/ds_mot_m0_2100.bin", "/system/models/ds_mot_m1_2100.bin",
                                DetectImageWidth, DetectImageHeight, 3); // 不知道什么原因，直接崩溃

    if (status != 0) {
        LOG(error) << "ds_pedestrian_hisi_init() failed, error: " << status;
        m_handle = NULL;
    } else {
        if (!licenseExisted && std::filesystem::exists(licensePath)) {
            system("sync");
        }
        LOG(info) << "algorithm initialize succeeded.";
    }

    return m_handle != nullptr;
}

void Algorithm::detect(const uint8_t *imageData) {
    if (m_handle == nullptr) {
        initialize();
    }
    if (m_handle == nullptr) return;
    NV21ToBGR24(imageData, m_buffer.data(), DetectImageWidth, DetectImageHeight);

    std::vector<PedestrianRect> bboxes;
    ds_pedestrian_det_hisi(m_handle, m_buffer.data(), bboxes);
}

void Algorithm::NV21ToBGR24(const unsigned char *nv21Data, unsigned char *bgr24Data, int width, int height) {
    cv::Mat nv21Image(height + height / 2, width, CV_8UC1, const_cast<unsigned char *>(nv21Data));
    cv::Mat bgrImage(height, width, CV_8UC3, bgr24Data);
    cv::cvtColor(nv21Image, bgrImage, cv::COLOR_YUV2BGR_NV21);
}
