//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2015 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
// 
#include "ProcessUtils.hpp"
#include "Information.hpp"

#include <QRegExp>
#include <QTreeWidget>
#include <QWidget>
#include <QString>

namespace mgx
{
  QTreeWidgetItem* getFolder(QString name, QHash<QString, QTreeWidgetItem*> &folders, 
									                                          QTreeWidget* tree)
  {
    if(folders.contains(name))
      return folders[name];
    int idx = name.lastIndexOf('/');
    QTreeWidgetItem* item = 0;
    if(idx == -1) {
      item = new QTreeWidgetItem(QStringList() << name);
      item->setExpanded(false);
      item->setFlags(Qt::ItemIsEnabled);
      tree->addTopLevelItem(item);
    } else {
      QString newname = name.left(idx);
      QTreeWidgetItem* parent = getFolder(newname, folders, tree);
      QString fn = name.mid(idx + 1);
      item = new QTreeWidgetItem(QStringList() << fn);
      item->setExpanded(true);
      item->setFlags(Qt::ItemIsEnabled);
      parent->addChild(item);
    }
    folders[name] = item;
    return item;
  }
  
  // Returns true if the item is visible
  bool filterItem(QTreeWidgetItem* item, const QRegExp& filter)
  {
    if(item->childCount() == 0) {
      bool selected = item->text(0).contains(filter);
      item->setHidden(not selected);
      return selected;
    } else {
      bool any_selected = false;
      for(int id = 0 ; id < item->childCount() ; ++id) {
        QTreeWidgetItem* child = item->child(id);
        any_selected |= filterItem(child, filter);
      }
      item->setHidden(not any_selected);
      return any_selected;
    }
  }
  
  void filterProcesses(QTreeWidget* tree, const QString& filter_text)
  {
    QRegExp filter(filter_text, Qt::CaseInsensitive);
    if(not filter.isValid() or filter_text.isEmpty())
      filter.setPattern(".");
    for(int top = 0 ; top < tree->topLevelItemCount() ; ++top) {
      QTreeWidgetItem* topItem = tree->topLevelItem(top);
      filterItem(topItem, filter);
    }
  }
}
