/* 
 *   \file  CMD5AndUrl.cpp
 *   \brief Defines class that supports MD5 and URL-read for images.
 *    
 *   \details  
 *   CMD5AndUrl supports functions such as MD5 extraction and reading image from URL. Note that
 *   not all functions ar eportable across Windows and Unix, since we use Windows library for MD5.
 *
 *   \date      November 4, 2011
 *   \copyright eBay Research Labs.
 */

// Include boost-specific headers.

#include <string>
#include <fstream>
#include <iostream>
#include <boost/format.hpp>

// Include openCV-specific headers.
#include <highgui.h>

#include "CMD5AndUrl.h"
#include "Log.h"
#include <openssl/md5.h>
#include "Base64.h"

using namespace std;
using namespace cv;

#define BUFSIZE 1024
#define MD5LEN  16

namespace Mantis
{

/*
 *   \brief Create MD5 hash based on RGB values.
 *
 *   \param [in]  img      Input matrix. This needs to be continuous (i.e.) not cropped using ROI.
 *   \param [out] md5Hash  MD5 hash.
 *   \return      Status code. -ve on error.
 */

std::string createMD5HashForImage(const Mat& img)
{
  std::string md5;
  
  unsigned char buf[MD5LEN];
  
  unsigned int numElements = img.rows * img.cols * img.channels();
  unsigned char *hopenssl = MD5(img.data, numElements, buf);
  md5 = mantis_base64_encode(buf, MD5LEN);
  return md5;
}

/*!
 *   \brief Read an image from data.
 *
 *   \param [in]  imageData     Image data.
 *   \return      Image.
 */
Mat readImage(const vector<unsigned char>& imageData)
{
Mat img;
  
try
  {
img = cv::imdecode(Mat(imageData), CV_LOAD_IMAGE_COLOR);
}
  
 catch (...)
   {
cout << "Unable to read image." << endl;
}
  
return img;
}

}

