//=========================================================================
//  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/workflows/ACE3P";
#elif defined(__APPLE__)
  relativePath = "../Resources/workflows/ACE3P";
#elif defined(__linux__)
#ifdef NDEBUG
  relativePath = "../../../share/cmb/workflows/ACE3P";
#else
  // Alternate path for development
  relativePath = "../../../install/share/workflows/ACE3P";
#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)
  {
#ifndef NDEBUG
    qDebug() << "Setting workflows directory to" << dirLocation.path();
#endif
    smtk::simulation::ace3p::Metadata::WORKFLOWS_DIRECTORY = dirLocation.path().toStdString();
  }
#ifdef NDEBUG
  else
  {
    qCritical() << "No workflow directory found for starting directory" << startingDir.path()
    << "and relative path" << relativePath;
  }
#endif
}
