/***************************************************************************

    source::worx xtree
    Copyright © 2024-2025 c.holzheuer
    christoph.holzheuer@gmail.com

    This program 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.

***************************************************************************/


#include <xqselectionmodel.h>
#include <xqitem.h>



//! konstruiert ein selectionmodel.

XQSelectionModel::XQSelectionModel(QAbstractItemModel* model)
    : QItemSelectionModel(model)
{

}


//! konstruiert ein selectionmodel.

XQSelectionModel::XQSelectionModel(QAbstractItemModel* model, QObject* parent)
    : QItemSelectionModel(model, parent)
{

}


//! jetzt die selektierten indices, wie die basisklasse, aber nur die innerhalt einer section.

void XQSelectionModel::select(const QItemSelection& selection, QItemSelectionModel::SelectionFlags command)
{
  // step #0: die ursprüngliche selection bestimmen
  const QModelIndexList list = selection.indexes();
  if (list.isEmpty() || selectedRows().isEmpty() )
    return QItemSelectionModel::select(selection, command);

  // step 01: den ersten index bestimmen
  QModelIndex firstValid = list.first();  
  if (hasSelection() )
    firstValid = selectedRows().first();

  // step 02: finde das erste item gültigem content node.
  XQNodePtr firstNode = XQItem::xqItemFromIndex(firstValid).contentNode();
  while( !firstNode)
  {
    firstValid = firstValid.siblingAtRow( firstValid.row()+1);
    firstNode = XQItem::xqItemFromIndex(firstValid).contentNode();
  }

  // step 03: selektiere nur knoten, die den gleichen tag_name haben, sich also
  // in der selben section befinden

  if( firstNode )
  {
    QItemSelection newSelection;
    for (const QModelIndex& idx : list)
    {
      XQNodePtr nextNode = XQItem::xqItemFromIndex(idx).contentNode();
      if (!nextNode || idx.data().toString().isEmpty() || nextNode->tag_name() != firstNode->tag_name() )
         break;
      newSelection.select(idx, idx);
    }
    return QItemSelectionModel::select(newSelection, command);
  }

  // fallback
  QItemSelectionModel::select(selection, command);
}
