/// GeDti2Handler.cpp
/**
*/

#include <wx/filename.h>
#include <wx/stdpaths.h>

#include <algorithm>
#include <set>
#include <math.h>

#include "Dictionary.h"
#include "DicomFile.h"
#include "StringConvert.h"
#include "Volume.h"
#include "GeEpiHandler.h"
#include "GeDti2Handler.h"

using namespace jcs;

///
/**
*/ 
GeDti2Handler::GeDti2Handler(const std::string& seriesUid)
: GeEpiHandler(seriesUid)
{
}


///
/**
*/ 
SeriesHandler::VolListType
GeDti2Handler::ReadVolIds(DicomFile& file)
{ 
  VolListType v = SeriesHandler::ReadVolIds(file);
  Dictionary* Excite = Excite_Dictionary::Instance();

  int image_number, number_of_slices;

  if (!file.Find("InstanceNumber", image_number)) {
    wxLogError(_("Instance number not found"));
  }

  if (!file.Find(Excite->Lookup("Locations_in_acquisition"), number_of_slices)) {
    wxLogError(_("Locations_in_acquisition not found"));
  }

  int vol_no = static_cast<int>(floor(static_cast<double>(image_number - 1) / number_of_slices) + 1);

  v.front().ids.push_back(itos(vol_no, 3));

  std::vector<double> g_value;
  std::string b_direction;
  double value;
  file.Find(Excite->Lookup("User_data_20"), value);
  g_value.push_back(value);

  file.Find(Excite->Lookup("User_data_21"), value);
  g_value.push_back(value);

  file.Find(Excite->Lookup("User_data_22"), value);
  g_value.push_back(value);

  int g_number;
  std::vector<std::vector <double> >::iterator pos;
  pos = find(gradients.begin(), gradients.end(), g_value);
  if (pos != gradients.end()) {
    g_number = distance(gradients.begin(), pos);
  }
  else {
    g_number = gradients.size();
    gradients.push_back(g_value);
  }

  v.front().ids.push_back(itos(g_number, 3));

  return v;
}


///
/**
*/
GradientInfo
GeDti2Handler::GetGradientInfo()
{
  GradientInfo info;

  Dictionary* Excite = Excite_Dictionary::Instance();

  std::map<VolId, std::string> volFileMap = GetVolIdsAndFiles();
  std::map<VolId, std::string>::iterator it = volFileMap.begin();
  std::map<VolId, std::string>::iterator it_end = volFileMap.end();

  for (;it != it_end; it++) {

    //std::vector<std::string> test = it->first.ids;
    //for (int t = 0; t < test.size(); ++t)
    //  wxLogMessage(test[t].c_str());
    
    info.values.push_back(0); // bvalue not found in these files.

    DicomFile file(it->second.c_str());

    double value;
    int err = file.Find(Excite->Lookup("User_data_20"), value);
    if (err > 0) { info.xGrads.push_back(value); }

    err = file.Find(Excite->Lookup("User_data_21"), value);
    if (err > 0) { info.yGrads.push_back(value); }

    err = file.Find(Excite->Lookup("User_data_22"), value);
    if (err > 0) { info.zGrads.push_back(value); }
  }

  // GE -- do not correct!
  //  std::vector<double> r = GetRotationMatrix(volFileMap.begin()->first);
  //  RotateGradInfo(info, r);

  return info;
}
