#include "InputFrameListModule.h"
#include "utils.hpp"

#include <fstream>
#include <ostream>
#include <iostream>
#include <algorithm>

//#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

namespace fs = boost::filesystem;

InputFrameListModule::InputFrameListModule(const std::string& _dirname)
  : mCurrentIdx(0), mInit(false), dirname(_dirname){
  loadImageList();
}

InputFrameListModule::~InputFrameListModule(void) { }


void InputFrameListModule::setFrameNumber(const unsigned int& frameNumber) {
  if (frameNumber < filenames.size())
    mCurrentIdx = frameNumber;
  else
    mCurrentIdx = filenames.size()-1;
}

bool InputFrameListModule::getNextFrame(cv::Mat& mat)
{
  bool success = false;
  if(mCurrentIdx < filenames.size()) {
      mat = cv::imread(dirname+filenames[mCurrentIdx++]);

      if(!mat.empty())
	success = true;
    }
	
  return success;
}

unsigned int InputFrameListModule::getNbFrames(void) {
  return filenames.size();
}

void InputFrameListModule::loadImageList(void) {
  for (fs::directory_iterator iter(dirname); iter!=fs::directory_iterator(); iter++)
    filenames.push_back(iter->path().filename().string());

  sort(filenames.begin(), filenames.end());

  if(!filenames.empty()) {
    std::cout << dirname+filenames[0] << std::endl;
    cv::Mat tmpImg = cv::imread(dirname+filenames[0]);
    mSize = cv::Size(tmpImg.cols, tmpImg.rows);
    mInit = true;
  }
}
