/*  FSLView - 2D/3D Interactive Image Viewer

    Authors:    Rama Aravind Vorray
		James Saunders
		David Flitney 
		Mark Jenkinson
		Stephen Smith

    FMRIB Image Analysis Group

    Copyright (C) 2002-2005 University of Oxford  */

/*  CCOPYRIGHT */

#include "clusterbrowser.h"
#include "clusterdata.h"
#include "filemanager.h"

#include <iostream>
#include <sstream>

#include <qcheckbox.h>
#include <q3listview.h>
#include <qcombobox.h>
//Added by qt3to4:
#include <QCloseEvent>

class ClusterListItem: public Q3ListViewItem
{
public:
  ClusterListItem(Q3ListView* v, Cluster::Handle c, TalairachCluster::Handle t, bool s):
    Q3ListViewItem(v),
    m_showTalairach(s), m_cluster(c), m_talCluster(t)
  {
    refresh();
  }

  void refresh()
  {
    if( m_cluster->initialised() ) {
      setText( 0, m_cluster->inqIndex().c_str());
      setText( 1, m_cluster->inqSize().c_str());
      setText( 2, m_cluster->inqP().c_str());
      setText( 3, m_cluster->inqMinusLog10P().c_str()); 
      setText( 4, m_cluster->inqMaxZ().c_str());
      setText(11, m_cluster->inqMaxCOPE().c_str());
      setText(15, m_cluster->inqMeanCOPE().c_str());
   } else {
      setText( 0, m_talCluster->inqIndex().c_str());
      setText( 1, m_talCluster->inqSize().c_str());
      setText( 2, m_talCluster->inqP().c_str());
      setText( 3, m_talCluster->inqMinusLog10P().c_str());
      setText( 4, m_talCluster->inqMaxZ().c_str());
      setText(11, m_talCluster->inqMaxCOPE().c_str());
      setText(15, m_talCluster->inqMeanCOPE().c_str());
    }

    BaseCluster::Handle temp;
    if(m_showTalairach)
      temp = m_talCluster;
    else temp = m_cluster;

    setText( 5, temp->inqMaxZx().c_str());
    setText( 6, temp->inqMaxZy().c_str());
    setText( 7, temp->inqMaxZz().c_str());
    setText( 8, temp->inqMaxCOGx().c_str());
    setText( 9, temp->inqMaxCOGy().c_str());
    setText(10, temp->inqMaxCOGz().c_str());

    setText(12, temp->inqMaxCOPEx().c_str());
    setText(13, temp->inqMaxCOPEy().c_str());
    setText(14, temp->inqMaxCOPEz().c_str());
  }

  int compare(Q3ListViewItem *i, int col, bool ascending) const
  {
    return key(col, ascending).toFloat() - i->key(col, ascending).toFloat();
  }

  Cluster::Handle getCluster()  const { return m_cluster; }
  TalairachCluster::Handle getTCluster() const { return m_talCluster; }

private:

  bool m_showTalairach;
  Cluster::Handle m_cluster; 
  TalairachCluster::Handle m_talCluster;
};

ClusterBrowser::ClusterBrowser(QWidget* parent, Image::Handle i,
			       Cursor::Handle c, ModelFit::Handle m):
  QMainWindow(parent),
  m_initialised(false),
  m_currentSelection(0),
  m_imageInfo(i->getInfo()), m_cursor(c), m_model(m)
{
  setupUi(this);

  try {
    statComboBox->clear();

    for(unsigned int i = 1; i <= m_model->numContrasts(); ++i) {
      QString basename(QString("%1/cluster_zstat%2").arg(m_model->featDir()).arg(i));

      ClusterList clusters, tclusters;
      string bname = basename.toUtf8().constData();

      if( FileManager::checkFileExists(bname + ".txt") )
    	FileManager::readClusters(bname + ".txt", clusters);
      if( FileManager::checkFileExists(bname + "_std.txt") )
    	FileManager::readTalairachClusters(bname + "_std.txt", tclusters);
      else if( FileManager::checkFileExists(bname + "_tal.txt") )
    	FileManager::readTalairachClusters(bname + "_tal.txt", tclusters);

      ClusterListPair cp(std::make_pair(clusters, tclusters));

      QString name(QString("zstat%1").arg(i));
      m_clusterTables.push_back(std::make_pair(name, cp));
      statComboBox->insertItem(name);
    }

    for(unsigned int i = 1; i <= m_model->numFtests(); ++i) {
      QString basename(QString("%1/cluster_zfstat%2").arg(m_model->featDir()).arg(i));

      ClusterList clusters, tclusters;
      string bname = basename.toUtf8().constData();

      if(FileManager::checkFileExists(bname + ".txt") )
    	FileManager::readClusters(bname + ".txt", clusters);
      if( FileManager::checkFileExists(bname + "_std.txt") )
    	FileManager::readTalairachClusters(bname + "_std.txt", tclusters);
      else if( FileManager::checkFileExists(bname + "_tal.txt") )
    	FileManager::readTalairachClusters(bname + "_tal.txt", tclusters);

      ClusterListPair cp(std::make_pair(clusters, tclusters));
      
      QString name(QString("zstatf%1").arg(i));
      m_clusterTables.push_back(std::make_pair(name, cp));
      statComboBox->insertItem(name);
    }
    
    m_initialised = true;

    on_statComboBox_currentIndexChanged(0);

  } catch (const std::ios::failure& e) {
    throw ClusterBrowser::Exception(std::string("ClusterBrowser::ClusterBrowser Couldn't initialise\n") + e.what());
  } catch (...) {
    throw;
   }
}

void ClusterBrowser::on_talairachCheckBox_clicked(bool s)
{
  m_showTalairach = s;
  on_statComboBox_currentIndexChanged(m_currentSelection);
}

void ClusterBrowser::on_statComboBox_currentIndexChanged(int n)
{
  if(!m_initialised)
    return;

  m_currentSelection = n;
  clusterListView->clear();
  for(int i = 0; i < clusterListView->columns(); ++i) {
    clusterListView->setColumnWidth(i, 0);
    clusterListView->setColumnWidthMode(i, Q3ListView::Maximum);
  }
#if (QT_VERSION < 0x030200)
  clusterListView->setSorting(1, false);
#else
  clusterListView->setSortColumn(1);
  clusterListView->setSortOrder(Qt::DescendingOrder);
#endif

  ClusterTable& t(m_clusterTables.at(n));
  ClusterListPair& p(t.second);
  ClusterList& clusters(p.first);
  ClusterList& tclusters(p.second);

  ClusterList::iterator ti = tclusters.begin();
  ClusterList::iterator ci = clusters.begin();
  
  while( (ci != clusters.end()) ||
	 (ti != tclusters.end()) ) {

    bool allowPlain(false);
    Cluster::Handle c = Cluster::create();     
    if( ci != clusters.end() ) {
      c = boost::dynamic_pointer_cast<Cluster>(*ci);
      ++ci;
      allowPlain = true;
    }

    bool allowTal(false); 
    TalairachCluster::Handle t = TalairachCluster::create();
    if( ti != tclusters.end() ) {
      t = boost::dynamic_pointer_cast<TalairachCluster>(*ti);
      ++ti;
      allowTal = true;
    }

    bool displayTal( (m_showTalairach && allowTal) || !allowPlain );
    new ClusterListItem(clusterListView, c, t, displayTal);

    if( !(allowPlain && allowTal) ) {
      talairachCheckBox->setDisabled(true);
      if( allowTal )
	talairachCheckBox->setChecked(true);
    } else
      talairachCheckBox->setEnabled(true);
  }
}

void ClusterBrowser::on_clusterListView_selectionChanged(Q3ListViewItem *item)
{
  if(ClusterListItem * cl = dynamic_cast<ClusterListItem*>(item)) {

    if( !talairachCheckBox->isChecked() ) {
      Cluster::Handle cluster  = cl->getCluster();
      cluster->setCursorToMaxZ(m_cursor);
    } else {
      TalairachCluster::Handle tcluster = cl->getTCluster();
      tcluster->setCursorToMaxZ(m_imageInfo, m_cursor);
    }
  }
}

void ClusterBrowser::closeEvent(QCloseEvent* e)
{
  emit windowClose(e);
}
