#include "common.h"

namespace maps::mrc::eye::pov {


Detection Detection::fromJson(const json::Value& value)
{
    auto bbox = value["bbox"];
    return Detection{
        .id=value["object_id"].as<db::TId>(),
        .bbox={bbox[0][0].as<size_t>(), bbox[0][1].as<size_t>(),
            bbox[1][0].as<size_t>(), bbox[1][1].as<size_t>()},
        .type = value["type"].as<std::string>()
    };
}

ImageData::ImageData(std::string encodedImage, common::ImageOrientation orientation)
    : encodedImage_(std::move(encodedImage))
    , orientation_(orientation)
{
    const auto image = decodedImage();
    scale_ = getImageScale(image);
    imageSize_ = common::transformByImageOrientation(
        common::Size(image.cols, image.rows),
        orientation_
    );
}

double ImageData::getImageScale(const cv::Mat& image)
{
    int maxSize = std::max(image.cols, image.rows);
    if (maxSize > DESIRED_MAX_SIZE) {
        return DESIRED_MAX_SIZE / static_cast<double>(maxSize);
    } else {
        return 1.;
    }
}

cv::Mat ImageData::decodedImage() const {
    return common::transformByImageOrientation(
        common::decodeImage(encodedImage_),
        orientation_);
}

cv::Mat ImageData::scaledDecodedImage() const {
    auto image = decodedImage();
    if (scale_ != 1.0) {
        cv::resize(image, image, cv::Size(), scale_, scale_);
    }
    return image;
}

} // namespace maps::mrc::eye::pov
