//
// 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.

/**
 * Misc.cpp - handling of resource paths.
 * Note: paths returned by these functions should not change depending on the filesystem state - from they user's perspective they should be hardcoded (e.g. don't use QDir.cd()).
 * That will reduce the number of possible places where files can hide and make installations uniform.
 */
#include "Misc.hpp"

#include <QTextStream>
#include <QCoreApplication>
#include <QString>
#include <QDir>
#include <QStandardPaths>
#include <iostream>
#include <QRegExp>
#include <QFileInfo>

#include <Config.hpp>
#include "Information.hpp"
#include "Dir.hpp"

#ifndef WIN32
#  include <unistd.h>
#  include <errno.h>
#endif


using namespace std;

namespace mgx 
{
  /**
   * @brief Returns path to resources
   */
  QDir resourceDir()
  {
    return QDir(MGXRESPATH);
  }
  
  /**
   * @brief Returns paths where the user can keep their processes.
   */
  QList<QDir> userProcessDirs()
  {
    QList<QDir> result;

    QDir dir = QDir::home().absoluteFilePath(".mgx/processes");
    result << dir;
    // This check doesn't really belong here inside the call. The create should be attempted once at most.
    if (!QDir().mkpath(dir.path())) {
      qWarning() << "Failed to create processes directory " << dir.path();
    }

    result << QDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation)).absoluteFilePath("processes");
    return result;
  }
  
  /**
   * @brief Returns directories where process files should be placed.
   *
   * Searches directories passed in MGXPROCPATH env variable in addition to default ones.
   */
  QList<QDir> processDirs()
  {
    QStringList paths = QString(MGXPROCPATH).split(":");
    const char *mgxprocpath = getenv("MGXPROCPATH");
    if (mgxprocpath != NULL) {
        paths << QString(mgxprocpath).split(":");
    }

    QList<QDir> result;
    foreach (QString path, paths) {
      result << QDir(path); // resolves paths relative to working directory
    }
    result << userProcessDirs();
    return result;
  }
  
  QDir includeDir()
  {
    return QDir(MGXPROCINCLPATH);
  }
  
  QDir libDir()
  {
    return QDir(MGXLIBPATH);
  }
  
  QDir docDir()
  {
    return QDir(MGXDOCPATH);
  }
}
