/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2015 Frederik Heber. All rights reserved.
 *
 *
 *   This file is part of MoleCuilder.
 *
 *    MoleCuilder 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 2 of the License, or
 *    (at your option) any later version.
 *
 *    MoleCuilder 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 MoleCuilder.  If not, see .
 */
/*
 * QtMoleculeListView.cpp
 *
 *  Created on: Jan 17, 2015
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "QtMoleculeListView.hpp"
#include "UIElements/Views/Qt4/MoleculeList/QtMoleculeList.hpp"
#include "UIElements/Views/Qt4/MoleculeList/QtMoleculeItemFactory.hpp"
#include "CodePatterns/MemDebug.hpp"
#include "CodePatterns/Observer/Notification.hpp"
#include "Actions/SelectionAction/Molecules/MoleculeByIdAction.hpp"
#include "Actions/SelectionAction/Molecules/NotMoleculeByIdAction.hpp"
#include "World.hpp"
QtMoleculeListView::QtMoleculeListView(QWidget * _parent) :
  QTreeView(_parent),
  Observer("QtMoleculeListView"),
  selecting(false)
{
  setSelectionMode(QAbstractItemView::MultiSelection);
  World::getInstance().signOn(this, World::SelectionChanged);
}
QtMoleculeListView::~QtMoleculeListView()
{
  World::getInstance().signOff(this, World::SelectionChanged);
}
void QtMoleculeListView::setModel(QtMoleculeList *_moleculelist)
{
  QTreeView::setModel(_moleculelist);
  // clicking a molecule means calling SelectionAction
  connect(
      selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
      this, SLOT(rowsSelected(const QItemSelection &, const QItemSelection &)));
}
void QtMoleculeListView::update(Observable *publisher)
{}
QModelIndex QtMoleculeListView::setIndexToLastColumn(const QModelIndex &_index) const
{
  QModelIndex return_index;
  QModelIndex parent_index = _index.parent();
  ASSERT (parent_index.isValid(),
      "QtMoleculeListView::setIndexToLastColumn() - _index has no valid parent.");
    return_index = parent_index.child(_index.row(), QtMoleculeItemFactory::OCCURRENCE);
//    return_index =
//        model()->invisibleRootItem()->child(
//            _index.row(),
//            QtMoleculeItemFactory::OCCURRENCE)->index();
  return return_index;
}
void QtMoleculeListView::rowsSelected(
    const QItemSelection& selected, const QItemSelection& deselected)
{
  if (selecting)
    return;
  selecting = true;
  // Select all molecules which belong to newly selected rows.
  QtMoleculeList *moleculelist = dynamic_cast(model());
  QModelIndex index;
  {
    QModelIndexList items = selected.indexes();
    molids_t ids;
    ids.reserve(items.size());
    foreach (index, items)
      if ((index.column() == 0) && (selectionModel()->isSelected(index))) {
        const moleculeId_t mol_id = moleculelist->IndexToMoleculeId(index);
        const molecule * const mol = const_cast(World::getInstance()).
            getMolecule(MoleculeById(mol_id));
        // check for invalid molecule
        if (mol_id < 0)
          continue;
        // means we are looking at deselection because of removal (in World)
        if (mol == NULL)
          continue;
        if (!World::getInstance().isSelected(mol))
            ids.push_back(mol_id);
        //std::cout << "select molecule" << std::endl;
      }
    if (!ids.empty())
      MoleCuilder::SelectionMoleculeById(ids);
  }
  // Unselect all molecules which belong to newly unselected rows.
  {
    QModelIndexList items = deselected.indexes();
    molids_t ids;
    ids.reserve(items.size());
    foreach (index, items)
      if ((index.column() == 0) && (!selectionModel()->isSelected(index))) {
        const moleculeId_t mol_id = moleculelist->IndexToMoleculeId(index);
        const molecule * const mol = const_cast(World::getInstance()).
            getMolecule(MoleculeById(mol_id));
        // check for invalid molecule
        if (mol_id < 0)
          continue;
        // means we are looking at deselection because of removal (in World)
        if (mol == NULL)
          continue;
        if (World::getInstance().isSelected(mol))
            ids.push_back(mol_id);
        //std::cout << "unselect molecule" << std::endl;
      }
    if (!ids.empty())
      MoleCuilder::SelectionNotMoleculeById(ids);
  }
  selecting = false;
}
void QtMoleculeListView::recieveNotification(Observable *publisher, Notification_ptr notification)
{
  if (dynamic_cast(publisher) != NULL) {
    switch (notification->getChannelNo()) {
      case World::SelectionChanged:
      {
        // obtain molecule selection from World and go through our selection step by step
        const std::vector selectedMolecules =
            const_cast(World::getInstance()).getSelectedMolecules();
        QItemSelection currently_selected = selectionModel()->selection();
        QtMoleculeList *moleculelist = static_cast(model());
        QItemSelection selected;
        QItemSelection deselected;
        std::set already_selected_indices;
        for (std::vector::const_iterator iter = selectedMolecules.begin();
            iter != selectedMolecules.end(); ++iter) {
          QtMoleculeItem *item = moleculelist->MoleculeIdToItem((*iter)->getId());
          if (item != NULL) {
            QModelIndex mol_index = item->index();
            if (!currently_selected.contains(mol_index))
                selected.select(mol_index, setIndexToLastColumn(mol_index));
            else
              already_selected_indices.insert(mol_index);
          }
        }
        {
          QModelIndex mol_index;
          foreach(mol_index, currently_selected.indexes()) {
            std::set::const_iterator iter =
                already_selected_indices.find(mol_index);
            if (iter == already_selected_indices.end())
              deselected.select(mol_index, setIndexToLastColumn(mol_index));
          }
        }
        selecting = true;
        if (!selected.indexes().empty())
          selectionModel()->select(selected, QItemSelectionModel::Select);
        if (!deselected.indexes().empty())
          selectionModel()->select(deselected, QItemSelectionModel::Deselect);
        selecting = false;
        break;
      }
      default:
        ASSERT(0, "QtMoleculeListView::recieveNotification() - cannot get here, not subscribed to channel "
            +toString(notification->getChannelNo()));
        break;
    }
  }
}
void QtMoleculeListView::subjectKilled(Observable *publisher)
{}