//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================
#include "plugin/pqACE3PPluginLocation.h"

#include "smtk/simulation/ace3p/Metadata.h"

#include <QDebug>
#include <QDir>
#include <QFileInfo>

pqACE3PPluginLocation::pqACE3PPluginLocation(QObject* parent)
  : Superclass(parent)
{
}

pqACE3PPluginLocation::~pqACE3PPluginLocation() {}

void pqACE3PPluginLocation::StoreLocation(const char* fileLocation)
{
  if (fileLocation == nullptr)
  {
    qDebug() << "Internal Error: pqACE3PPluginLocation::StoreLocation() called with null pointer";
    return;
  }

  // Check whether or not this is an installed package
  QFileInfo fileInfo(fileLocation);
  QDir dirLocation(fileInfo.absoluteDir());

#ifndef NDEBUG
  qDebug() << "Plugin location: " << fileLocation;
  qDebug() << "Plugin directory: " << dirLocation.path();
#endif

  // Save starting directory for diagnostics
  QDir startingDir(dirLocation);

  // Look for path to simulation workflows
  // * Depends on superbuild-packaging organization
  // * Which is platform-dependent
  QString relativePath;
#if defined(_WIN32)
  relativePath = "../../../share/cmb";
#elif defined(__APPLE__)
  relativePath = "../Resources";
#elif defined(__linux__)
#ifdef NDEBUG
  relativePath = "../../../share/cmb";
#else
  // Alternate path for development
  relativePath = "../../../install/share";
#endif
#endif

  if (relativePath.isEmpty())
  {
#ifdef NDEBUG
    qCritical() << "Missing installed path to workflow files";
#endif
    return;
  }

  // Check if directory exists
  bool exists = dirLocation.cd(relativePath);
  if (!exists)
  {
#ifdef NDEBUG
    QString path = startingDir.path() + "/" + relativePath;
    if (smtk::simulation::ace3p::Metadata::WORKFLOWS_DIRECTORY.empty())
    {
      qCritical() << "Plugin workflows directory not found:" << path;
    }
#endif
    return;
  }

  this->locateWorkflows(dirLocation);
}

void pqACE3PPluginLocation::locateWorkflows(const QDir& pluginResourcesDirectory) const
{
  QDir dir(pluginResourcesDirectory);
  QString relativePath("workflows/ACE3P");
  bool exists = dir.cd(relativePath);
  if (!exists)
  {
    qCritical() << "No workflow directory found for starting directory"
                << pluginResourcesDirectory.absolutePath() << "and relative path" << relativePath;
    return;
  }

#ifndef NDEBUG
  qDebug() << "Setting workflows directory to" << dir.absolutePath();
#endif
  smtk::simulation::ace3p::Metadata::WORKFLOWS_DIRECTORY = dir.absolutePath().toStdString();
}
