/***************************************************************************
**
**  This file is part of geopsy.
**
**  geopsy is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  geopsy is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2006-05-03
**  Copyright: 2006-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include <GeopsyCore.h>

#include "Engine.h"
#include "SignalTableView.h"
#include "SignalTableItem.h"
#include "SignalTableDelegate.h"
#include "MainWindow.h"

SignalTableView::SignalTableView(SubSignalPool * subPool, QWidget * parent)
    : QTableView(parent)
{
  TRACE;
  SignalTableItem * item=new SignalTableItem(subPool, this);
  setModel(item);
  setItemDelegate(new SignalTableDelegate(this) );
  setSelectionBehavior(QAbstractItemView::SelectRows);
  setSelectionMode(QAbstractItemView::ExtendedSelection);
  setEditTriggers(QAbstractItemView::AllEditTriggers);
}

SignalTableView::~SignalTableView()
{
  TRACE;
}

/*!
  Call this slot before changing one signal in the view.
*/
void SignalTableView::beginSignalChange(Signal * sig)
{
  TRACE;
  SignalTableItem& m=*static_cast<SignalTableItem *>(model());
  if(!sig) {
    m.beginChange();
  }
}

/*!
  Call this slot after changing one signal in the view.
*/
void SignalTableView::endSignalChange(Signal * sig)
{
  TRACE;
  SignalTableItem& m=*static_cast<SignalTableItem *>(model());
  if(sig) {
    int i=m.subPool()->indexOf(sig);
    if(i>=0) {
      dataChanged(m.index(0, i), m.index(m.columnCount(), i));
    }
  } else {
    m.endChange();
  }
}

/*!
  Returns the selected signals into a SubSignalPool
*/
void SignalTableView::getSelection(SubSignalPool& sel)
{
  TRACE;
  QItemSelectionModel& selModel=*selectionModel();
  QModelIndex rIndex=rootIndex();
  SignalTableItem& m=*static_cast<SignalTableItem *>(model());
  const SubSignalPool& subPool=*m.subPool();
  int n=subPool.count();

  for(int i=0;i < n;i++ ) {
    if(selModel.rowIntersectsSelection(i, rIndex)) {
      sel.addSignal(subPool.at(i) );
    }
  }
}

/*!
  Returns the current data fields and let any external function to change it
*/
MetaDataFieldList& SignalTableView::dataFields()
{
  TRACE;
  SignalTableItem * m=static_cast<SignalTableItem *>(model());
  return m->dataFields();
}
