//=============================================================================
//
//  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 "smtk/simulation/windtunnel/qt/qtSessionData.h"

#include "smtk/project/Project.h"

#include <QDir>
#include <QFileInfo>

namespace
{
// Singleton instance
static smtk::simulation::windtunnel::qtSessionData* g_instance = nullptr;

QString projectPath(const smtk::project::ProjectPtr project, const QString subdirectory = QString())
{
  if (project == nullptr) // safety first
  {
    return "";
  }

  QFileInfo projectFileInfo(project->location().c_str());
  QDir projectDir = projectFileInfo.absoluteDir();
  if (subdirectory.isEmpty())
  {
    return projectDir.absolutePath();
  }
  // (else)
  if (!projectDir.cd(subdirectory))
  {
    return QString();
  }

  // (else)
  return projectDir.absolutePath();
}

} // namespace

namespace smtk
{
namespace simulation
{
namespace windtunnel
{

qtSessionData* qtSessionData::instance(QObject* parent)
{
  if (!g_instance)
  {
    g_instance = new qtSessionData(parent);
  }

  if (g_instance->parent() == nullptr && parent)
  {
    g_instance->setParent(parent);
  }

  return g_instance;
}

qtSessionData::~qtSessionData()
{
  if (g_instance == this)
  {
    g_instance = nullptr;
  }

  QObject::disconnect(this);
}

bool qtSessionData::unsetProject(std::shared_ptr<smtk::project::Project> p)
{
  if (m_project == p)
  {
    m_project.reset();
    return true;
  }

  // (else)
  return false;
}

QString qtSessionData::projectDirectory() const
{
  return projectPath(m_project);
}

QString qtSessionData::assetsDirectory() const
{
  return projectPath(m_project, "assets");
}

QString qtSessionData::foamDirectory() const
{
  return projectPath(m_project, "foam");
}

QString qtSessionData::resourcesDirectory() const
{
  return projectPath(m_project, "resources");
}

} // namespace windtunnel
} // namespace simulation
} // namespace smtk
