/*=========================================================================

   Program: ParaView
   Module:    pqFileDialogFavoriteModel.cxx

   Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
   All rights reserved.

   ParaView is a free software; you can redistribute it and/or modify it
   under the terms of the ParaView license version 1.2.

   See License_v1.2.txt for the full ParaView license.
   A copy of this license can be obtained by contacting
   Kitware Inc.
   28 Corporate Drive
   Clifton Park, NY 12065
   USA

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

#include "pqFileDialogFavoriteModel.h"

#include <QApplication>
#include <QBrush>
#include <QDir>
#include <QFont>
#include <QStyle>
#include <pqCoreConfiguration.h>
#include <pqFileDialogModel.h>
#include <pqServer.h>
#include <pqServerConfiguration.h>
#include <pqServerResource.h>
#include <pqSettings.h>
#include <vtkClientSession.h>
#include <vtkCollection.h>
#include <vtkCollectionIterator.h>
#include <vtkPVFileInformation.h>
#include <vtkPVGUIApplication.h>
#include <vtkRemoteObjectProvider.h>
#include <vtkSMIntVectorProperty.h>
#include <vtkSMProxy.h>
#include <vtkSMSessionProxyManager.h>
#include <vtkSMStringVectorProperty.h>
#include <vtkSmartPointer.h>
#include <vtkStringList.h>

#include "pqSMAdaptor.h"

bool pqFileDialogFavoriteModel::AddExamplesInFavorites = true;

/////////////////////////////////////////////////////////////////////
// Icons
// NOLINTNEXTLINE(readability-redundant-member-init)
Q_GLOBAL_STATIC(pqFileDialogModelIconProvider, Icons);

//-----------------------------------------------------------------------------
pqFileDialogFavoriteModel::pqFileDialogFavoriteModel(pqServer* server, QObject* p)
  : Superclass(p)
{
  this->Server = server;
  // We need to determine the URI for this server to get the list of favorites directories
  // from the pqSettings. If server==nullptr, we use the "builtin:" resource.
  pqServerResource resource = server ? server->resource() : pqServerResource("builtin:");

  QString uri = resource.configuration().URI();
  vtkPVGUIApplication* core = vtkPVGUIApplication::GetInstance();
  pqSettings* settings = core->GetSettings();

  this->FileInformation = vtkSmartPointer<vtkPVFileInformation>::New();

  QString key = QString("UserFavorites/%1").arg(uri);
  if (settings->contains(key))
  {
    QVariantList const fileInfos = settings->value(key).toList();
    // ensure that the directories exist.
    for (QVariant const& fileInfo : fileInfos)
    {
      auto fileInfoList = fileInfo.toList();
      this->FavoriteList.push_back(pqFileDialogFavoriteModelFileInfo{
        fileInfoList[0].toString(), fileInfoList[1].toString(), fileInfoList[2].toInt() });
    }
  }
  else
  {
    this->RetrieveFavoritesFromSystem();
  }
  this->SettingsKey = key;
}

//-----------------------------------------------------------------------------
pqFileDialogFavoriteModel::~pqFileDialogFavoriteModel()
{
  vtkPVGUIApplication* core = vtkPVGUIApplication::GetInstance();
  pqSettings* settings = core->GetSettings();
  if (settings)
  {
    QVariantList favoriteListVariant;
    favoriteListVariant.reserve(this->FavoriteList.size());
    for (pqFileDialogFavoriteModelFileInfo const& fileInfo : this->FavoriteList)
    {
      favoriteListVariant.push_back(
        QVariant{ { fileInfo.Label, fileInfo.FilePath, fileInfo.Type } });
    }
    settings->setValue(this->SettingsKey, favoriteListVariant);
  }
}

//-----------------------------------------------------------------------------
QString pqFileDialogFavoriteModel::filePath(const QModelIndex& index) const
{
  return this->data(index, Qt::UserRole).toString();
}

//-----------------------------------------------------------------------------
bool pqFileDialogFavoriteModel::isDir(const QModelIndex& index) const
{
  if (index.row() >= this->FavoriteList.size())
  {
    return false;
  }

  const pqFileDialogFavoriteModelFileInfo& file = this->FavoriteList[index.row()];
  return vtkPVFileInformation::IsDirectory(file.Type);
}

//-----------------------------------------------------------------------------
QVariant pqFileDialogFavoriteModel::data(const QModelIndex& idx, int role) const
{
  if (!idx.isValid() || idx.row() >= this->FavoriteList.size() || idx.column() != 0)
  {
    return QVariant();
  }

  const auto* app = vtkPVCoreApplication::GetInstance();
  const pqFileDialogFavoriteModelFileInfo& file = this->FavoriteList[idx.row()];
  auto filePath = file.FilePath;
  // If it is the Examples dir placeholder, replace it with the real path to the examples.
  if (filePath == "_examples_path_")
  {
    // FIXME when the shared resources dir is not found, this is equal to `/examples`. This might be
    // confusing for people without the `Examples` directory (mostly ParaView devs). This directory
    // can be hidden by setting the `AddExamplesInFavoritesBehavior` to `false`.
    filePath = QString::fromStdString(app->GetExampleFilesDirectory());
  }
  switch (role)
  {
    case Qt::DisplayRole:
    case Qt::EditRole:
      return file.Label;
    case Qt::UserRole:
      return filePath;
    case Qt::ItemDataRole::ToolTipRole:
      if (QDir(filePath).exists())
      {
        return filePath;
      }
      else
      {
        return filePath + " (Warning: does not exist)";
      }
    case Qt::ItemDataRole::FontRole:
      if (QDir(filePath).exists())
      {
        return {};
      }
      else
      {
        QFont font;
        font.setItalic(true);
        return font;
      }

    case Qt::ItemDataRole::ForegroundRole:
      if (QDir(filePath).exists())
      {
        return {};
      }
      else
      {
        QBrush brush;
        brush.setColor(QApplication::palette().color(QPalette::Disabled, QPalette::WindowText));
        return brush;
      }

    case Qt::DecorationRole:
      if (QDir(filePath).exists())
      {
        return Icons()->icon(static_cast<vtkPVFileInformation::FileTypes>(file.Type));
      }
      else
      {
        return QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning);
      }
  }

  return QVariant();
}

//-----------------------------------------------------------------------------
int pqFileDialogFavoriteModel::rowCount(const QModelIndex&) const
{
  return this->FavoriteList.size();
}

//-----------------------------------------------------------------------------
QVariant pqFileDialogFavoriteModel::headerData(int section, Qt::Orientation, int role) const
{
  switch (role)
  {
    case Qt::DisplayRole:
      switch (section)
      {
        case 0:
          return tr("Favorites");
      }
  }

  return QVariant();
}

//-----------------------------------------------------------------------------
void pqFileDialogFavoriteModel::addToFavorites(QString const& dirPath)
{
  QFileInfo fileInfo(dirPath);
  if (!fileInfo.isDir())
  {
    return;
  }

  QString const cleanDirPath = QDir::cleanPath(fileInfo.absoluteFilePath());

  QList<pqFileDialogFavoriteModelFileInfo>& favoriteList = this->FavoriteList;
  auto foundIter = std::find_if(favoriteList.begin(), favoriteList.end(),
    [&cleanDirPath](pqFileDialogFavoriteModelFileInfo const& favInfo) {
      return favInfo.FilePath == cleanDirPath;
    });

  if (foundIter != favoriteList.end())
  {
    // No need to add to favorites because it is already present
    return;
  }

  int type = fileInfo.isSymLink() ? vtkPVFileInformation::FileTypes::DIRECTORY_LINK
                                  : vtkPVFileInformation::FileTypes::DIRECTORY;

  this->beginInsertRows(QModelIndex(), favoriteList.size(), favoriteList.size());
  favoriteList.push_back(
    pqFileDialogFavoriteModelFileInfo{ fileInfo.baseName(), cleanDirPath, type });
  this->endInsertRows();
}

//-----------------------------------------------------------------------------
void pqFileDialogFavoriteModel::removeFromFavorites(QString const& dirPath)
{
  const auto* app = vtkPVCoreApplication::GetInstance();
  QString cleanDirPath = QDir::cleanPath(QFileInfo(dirPath).absoluteFilePath());
  // Check if this is the Examples directory, because it is not stored like the other directories
  if (cleanDirPath == QString::fromStdString(app->GetExampleFilesDirectory()))
  {
    cleanDirPath = "_examples_path_";
  }

  auto foundIter = std::find_if(this->FavoriteList.begin(), this->FavoriteList.end(),
    [&](pqFileDialogFavoriteModelFileInfo const& fileInfo) {
      return fileInfo.FilePath == cleanDirPath;
    });

  if (foundIter == this->FavoriteList.end())
  {
    return;
  }

  int const row = std::distance(this->FavoriteList.begin(), foundIter);
  this->beginRemoveRows(QModelIndex(), row, row);
  this->FavoriteList.erase(foundIter);
  this->endRemoveRows();
}

//-----------------------------------------------------------------------------
void pqFileDialogFavoriteModel::resetFavoritesToDefault()
{
  this->RetrieveFavoritesFromSystem();
}

//-----------------------------------------------------------------------------
bool pqFileDialogFavoriteModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
  if (index.isValid() && role == Qt::EditRole)
  {
    this->FavoriteList[index.row()].Label = value.toString();

    Q_EMIT this->dataChanged(index, index);

    return true;
  }

  return false;
}

//-----------------------------------------------------------------------------
Qt::ItemFlags pqFileDialogFavoriteModel::flags(const QModelIndex& index) const
{
  if (index.isValid())
  {
    return Qt::ItemFlag::ItemIsEditable | Superclass::flags(index);
  }

  return Superclass::flags(index);
}

//-----------------------------------------------------------------------------
void pqFileDialogFavoriteModel::LoadFavoritesFromSystem()
{
  this->FavoriteList.clear();
  if (pqFileDialogFavoriteModel::AddExamplesInFavorites)
  {
    // Adds the Examples entry in the favorites
    // This is using `_examples_path_` as a placeholder because storing the absolute path to the
    // `Examples` directory causes issues when switching to another ParaView version, because this
    // path would still point to the previous version's examples. This entry is added even if the
    // `Examples` directory is not present.
    this->FavoriteList.push_back(pqFileDialogFavoriteModelFileInfo{
      "Examples", "_examples_path_", vtkPVFileInformation::DIRECTORY });
  }
  vtkCollectionIterator* iter = this->FileInformation->GetContents()->NewIterator();
  for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())
  {
    vtkPVFileInformation* cur_info = vtkPVFileInformation::SafeDownCast(iter->GetCurrentObject());
    if (!cur_info)
    {
      continue;
    }
    this->FavoriteList.push_back(pqFileDialogFavoriteModelFileInfo{
      cur_info->GetName(), QDir::cleanPath(cur_info->GetFullPath()), cur_info->GetType() });
  }
}

//-----------------------------------------------------------------------------
void pqFileDialogFavoriteModel::RetrieveFavoritesFromSystem()
{
  this->FileInformation->Initialize();
  this->FileInformation->SetListSpecialDirectories(true);

  auto* session = this->Server->session();
  auto packet = vtkRemoteObjectProvider::GatherInformation(
    this->FileInformation, /* no corresponding remote Object*/ 0u);
  auto coordination = session->GetCoordination();
  auto eventual = session->SendRequest(
    /** FIXME**/ vtkClientSession::ServiceTypes::DATA_SERVER, std::move(packet));
  eventual.GetObservable().observe_on(coordination).subscribe([this](const vtkPacket& packet) {
    if (vtkRemoteObjectProvider::ParseResponse(packet, this->FileInformation))
    {
      this->beginResetModel();
      this->LoadFavoritesFromSystem();
      this->endResetModel();
    }
  });
}
