#include "image_utils.h"

#include <maps/libs/log8/include/log8.h>

#include <maps/wikimap/mapspro/services/mrc/libs/common/include/exif.h>
#include <maps/wikimap/mapspro/services/mrc/libs/common/include/opencv.h>

namespace maps::wiki::toloka {

namespace {

using namespace maps::mrc::common;

auto normalizedMat(const std::string& imageData)
{
    auto mat = decodeImage(imageData);
    INFO() << "Source image, width: " << mat.cols << " height: " << mat.rows;

    auto imageOrientation = parseImageOrientationFromExif(imageData);
    if (!imageOrientation) {
        return mat;
    }

    INFO() << "Orientation: " << *imageOrientation;
    auto rotated = transformByImageOrientation(mat, *imageOrientation);
    INFO() << "Transformed image, width: " << rotated.cols << " height: " << rotated.rows;
    return rotated;
}

} // namespace

std::string shrinkImage(const std::string& imageData, size_t scale)
{
    const auto mat = normalizedMat(imageData);

    const Size size(mat.cols / scale, mat.rows / scale);
    const auto newMat = fitImageTo(mat, size);
    INFO() << "Shrinked image, width: " << newMat.cols << " height: " << newMat.rows;

    return toBlob(encodeImage(newMat));
}

} // namespace maps::wiki::toloka
