/// AchievaDtiHandler.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 "SeriesHandler.h"
#include "AchievaDtiHandler.h"

using namespace jcs;

///
/**
*/
AchievaDtiHandler::AchievaDtiHandler(const std::string& seriesUid)
: SeriesHandler(seriesUid)
{
}


///
/**
*/
SeriesHandler::VolListType
AchievaDtiHandler::ReadVolIds(DicomFile& file)
{ 
  VolListType v = SeriesHandler::ReadVolIds(file);
  Dictionary* Achieva = PhilipsMr_Dictionary::Instance();

  std::vector<double> g_value;
  std::string b_direction;

  double value;
  file.Find(Achieva->Lookup("Diffusion_B-Factor"), value);
  g_value.push_back(value);

  file.Find(Achieva->Lookup("Diffusion_Direction_RL"), value);
  g_value.push_back(value);

  file.Find(Achieva->Lookup("Diffusion_Direction_AP"), value);
  g_value.push_back(value);

  file.Find(Achieva->Lookup("Diffusion_Direction_FH"), 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
AchievaDtiHandler::GetGradientInfo()
{
  GradientInfo info;

  Dictionary* Achieva = PhilipsMr_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());

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

    double value;
    file.Find(Achieva->Lookup("Diffusion_B-Factor"), value);
    info.values.push_back(value);

    file.Find(Achieva->Lookup("Diffusion_Direction_RL"), value);
    info.xGrads.push_back(value);

    file.Find(Achieva->Lookup("Diffusion_Direction_AP"), value);
    info.yGrads.push_back(value);

    file.Find(Achieva->Lookup("Diffusion_Direction_FH"), value);
    info.zGrads.push_back(value);
  }

  std::vector<double> r = GetRotationMatrix(volFileMap.begin()->first);

  RotateGradInfo(info, r);
  return info;
}
