#include <maps/wikimap/mapspro/services/mrc/libs/common/include/types.h>
#include <maps/libs/common/include/exception.h>

namespace maps::mrc::common {

namespace {

constexpr auto READ_MODE = CV_LOAD_IMAGE_COLOR | cv::IMREAD_IGNORE_ORIENTATION;

} //  namespace

Size getThumbnailSize(size_t width, size_t height)
{
    return getThumbnailSize(Size{width, height});
}

Size getThumbnailSize(const Size& size)
{
    constexpr std::size_t THUMBNAIL_HEIGHT_PX = 160;

    const size_t width = size.width * THUMBNAIL_HEIGHT_PX / size.height;
    return {width, THUMBNAIL_HEIGHT_PX};
}

cv::Mat decodeImage(const Bytes& bytes) { return cv::imdecode(bytes, READ_MODE); }

cv::Mat decodeImage(const Blob& blob) {
    return cv::imdecode(
        cv::_InputArray(reinterpret_cast<const Byte*>(blob.data()), blob.size()),
        READ_MODE
    );
}

Bytes encodeImage(const cv::Mat& image, int jpegLumaQuality)
{
    std::vector<int> params;
    if (jpegLumaQuality) {
        params.push_back(CV_IMWRITE_JPEG_LUMA_QUALITY);
        params.push_back(jpegLumaQuality);
    }

    Bytes result;
    cv::imencode(".jpg", image, result, params);
    return result;
}

} // namespace maps::mrc::common
