/* massXpert - the true massist's program.
   --------------------------------------
   Copyright(C) 2006,2007 Filippo Rusconi

   http://www.massxpert.org/massXpert

   This file is part of the massXpert project.

   The massxpert project is the successor to the "GNU polyxmass"
   project that is an official GNU project package(see
   www.gnu.org). The massXpert project is not endorsed by the GNU
   project, although it is released ---in its entirety--- under the
   GNU General Public License. A huge part of the code in massXpert
   is actually a C++ rewrite of code in GNU polyxmass. As such
   massXpert was started at the Centre National de la Recherche
   Scientifique(FRANCE), that granted me the formal authorization to
   publish it under this Free Software License.

   This software is free software; you can redistribute it and/or
   modify it under the terms of the GNU  General Public
   License version 3, as published by the Free Software Foundation.
   

   This software is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this software; if not, write to the

   Free Software Foundation, Inc.,

   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/


/////////////////////// Qt includes
#include <QApplication>
#include <QDir>
#include <QDebug>

#ifdef Q_WS_MAC
#include <CoreFoundation/CoreFoundation.h>
#endif

/////////////////////// Local includes
#include "config.h"
#include "configSettings.hpp"



namespace massXpert
{

  //! Initializes the members of the class.
  /*! The initialization of the members of the class involves
    determining where the system and user configuration directories are
    located.
  
    \li System configuration directory: it is set by the variable
    MASSXPERT_DATA_DIR in the config.h file. Thus, this directory is set
    at compile time.

    \li User configuration directory: it is determined at run time by
    inspecting the value returned by the call to QDir::homePath
   (). Under Windows this function will return the directory of the
    current user's profile. Typically, this is: "C:\\Documents and
    Settings\\Username". Under non-Windows operating systems the HOME
    environment variable is used if it exists, otherwise the path
    returned by the rootPath() function is used(this latter function
    returns '/' on non-Windows systems and "c:\\" on Windows).
  
    Inside the User/System configuration directories a "pol-chem-defs"
    directory will contain a number of files:

    \li \c massxpert-pol-chem-defs-cat is a catalogue that relates
    polymer chemistry definition names with the corresponding
    directories where the definition data are to be found. For example,
    one line from that file might be:

    protein=/home/rusconi/.massxpert/pol-chem-defs/protein/protein.xml

    This line tells that the "protein" polymer chemistry definition file
    is named protein.xml and that it is located, along with all the
    other data files pertaining to that same polymer chemistry
    definition, in the /home/rusconi/.massxpert/pol-chem-defs/protein
    directory.

    During initialization, if system configuration directories are not
    found, then these are not created. Which is not the case for the
    user configuration directories: if these are not found, they are
    created, thus yielding ---on a UNIX-like system for example--- the
    following directories:

    $HOME/.massxpert and $HOME/.massxpert/pol-chem-defs

    The user might then populate these directories with data suiting her
    needs.

    \return true if initialization was successful, false otherwise.
  */
  bool 
  ConfigSettings::initializeSystemConfig()
  {
    QDir dir;

    // First off, some general concepts.

    // When the software is built, a configuration process will
    // provide values for a number of #defined variables, depending on
    // the platform on which the software is built.

    // For example on MS-Windows, the following variables are defined:

    /*
      #define MASSXPERT_BIN_DIR C:/Program Files/massxpert
      #define MASSXPERT_DATA_DIR C:/Program Files/massxpert/data
      #define MASSXPERT_PLUGIN_DIR C:/Program Files/massxpert/plugins
      #define MASSXPERT_LOCALE_DIR C:/Program Files/massxpert/locales
      #define MASSXPERT_USERMAN_DIR C:/Program Files/massxpert/doc/usermanual
    
    */

    // On GNU/Linux, instead, the following variables are defined:

    /*
      #define MASSXPERT_BIN_DIR /usr/local/bin
      #define MASSXPERT_DATA_DIR /usr/local/share/massxpert
      #define MASSXPERT_PLUGIN_DIR /usr/local/lib/massxpert/plugins
      #define MASSXPERT_LOCALE_DIR /usr/local/share/massxpert/locales
      #define MASSXPERT_USERMAN_DIR: /usr/local/share/doc/massxpert/usermanual
    */

    /* On Mac OS X, instead, the software is built using not cmake,
       but qmake, and that makes it buildable using Xcode. The build
       generates in this case a Mac Bundle massXpert.app, which
       installs anywhere as long as its internal structure is
       conserved. There is an API to identify from which location the
       bundle is used(double-clicking onto the massXpert.app
       icon). We use that API to get the bundle directory, which might
       be something like /Applications/massXpert.app if the bundle was
       dropped into /Applications.
    */

#if defined(Q_WS_MAC)
    CFURLRef bundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    
    CFStringRef macPath = 
      CFURLCopyFileSystemPath(bundleRef, kCFURLPOSIXPathStyle);
    
    QString bundleDir = 
      CFStringGetCStringPtr(macPath, CFStringGetSystemEncoding());
    
    CFRelease(bundleRef);
    CFRelease(macPath);
#endif


    // Now, it might be of interest for the user to install the
    // software in another location than the canonical one. In this
    // case, the program should still be able to access the data.

    // This is what this function is for. This function will try to
    // establish if the data that were built along the software
    // package are actually located in the cnaonical places listed
    // above. If not, this function returns false. The caller might
    // then take actions to let the user manually instruct the program
    // of where the data are located.

    // All this procedure is setup so as to let the user install the
    // software wherever she wants.


      /////////////////// MASSXPERT_DATA_DIR ///////////////////
      /////////////////// MASSXPERT_DATA_DIR ///////////////////
      /////////////////// MASSXPERT_DATA_DIR ///////////////////
    
#ifdef Q_WS_MAC
    dir.setPath(bundleDir + QDir::separator() + "Contents" +
		 QDir::separator() + "Resources" +
		 QDir::separator() + "data");
#else
    dir.setPath(QString(MASSXPERT_DATA_DIR));
#endif

    // The path must be absolute and must exist.

    if (!dir.isAbsolute())
      return false;
    
    if (!dir.exists())
      return false;

    m_systemDataDir = dir.absolutePath();
    
    // OK, the directory exists, we still have to make sure that we
    // can find the proper data in it. Namely the directory where the
    // data are acutally stored(pol-chem-defs subdirectory).

    dir.setPath(dir.absolutePath() + 
		 QDir::separator() + "pol-chem-defs");
    
    if (!dir.exists())
      return false;

    m_systemPolChemDefCatDir = dir.absolutePath();

    // Finally, make sure the system catalogue file of all the polymer
    // chemistry definitions shipped in the program package, that sits
    // in the "pol-chem-defs" directory.

    QString filePath = dir.absolutePath() +
      QDir::separator() + "massxpert-pol-chem-defs-cat";
    
    if (!QFile::exists(filePath))
      return false;
    

      /////////////////// MASSXPERT_PLUGIN_DIR ///////////////////
      /////////////////// MASSXPERT_PLUGIN_DIR ///////////////////
      /////////////////// MASSXPERT_PLUGIN_DIR ///////////////////

#ifdef Q_WS_MAC
    dir.setPath(bundleDir + QDir::separator() + "Contents" +
		 QDir::separator() + "Plugins");
#else
    dir.setPath(QString(MASSXPERT_PLUGIN_DIR));
#endif
    
    // The path must be absolute and must exist.
    
    if (!dir.isAbsolute())
      return false;
    
    if (!dir.exists())
      return false;
    
    // At the moment there are three plugins:

    // libnumeralsLocaleConverterPlugin.so 
    
    // libmassListSorterPlugin.so
    
    // libseqToolsPlugin.so
    
    QString libname;
    
#ifdef Q_OS_LINUX
    libname = "libnumeralsLocaleConverterPlugin.so";
#elif defined Q_OS_DARWIN
    libname = "libnumeralsLocaleConverterPlugin.dylib";
#elif defined Q_OS_WIN32
    libname ="libnumeralsLocaleConverterPlugin.dll";
#endif
    
    filePath = QString(dir.absolutePath() +
			QDir::separator() +
			libname);
    
    // But in fact, we cannot assume that there are plugins.
    //    if (!QFile::exists(filePath))
    //  return false;

    m_systemPluginDir = dir.absolutePath();
    

      /////////////////// MASSXPERT_LOCALE_DIR ///////////////////
      /////////////////// MASSXPERT_LOCALE_DIR ///////////////////
      /////////////////// MASSXPERT_LOCALE_DIR ///////////////////

#ifdef Q_WS_MAC
    dir.setPath(bundleDir + QDir::separator() + "Contents" +
		 QDir::separator() + "Locales");
#else
    dir.setPath(QString(MASSXPERT_LOCALE_DIR));
#endif
    
    // The path must be absolute and must exist.

    if (!dir.isAbsolute())
      return false;
    
    if (!dir.exists())
      return false;
    
    // At the moment there is the french translation: massxpert_fr.qm
    
    filePath = QString(dir.absolutePath() +
			QDir::separator() +
			"massxpert_fr.qm");
    
    if (!QFile::exists(filePath))
      return false;
    
    m_systemLocalizationDir = dir.absolutePath();
    return true;
  }


  bool 
  ConfigSettings::initializeUserConfig()
  {
    QDir dir;


    // First off, some general concepts.

    // massXpert should let the user define any polymer chemistry of
    // his requirement, without needing the root priviledges for
    // installation of these new data.

    // This is why massXpert allows for personal data directories
    // modelled on the same filesystem scheme as for the system data
    // directory. 

    // When the program is run, it check if the .massxpert directory
    // exists in the home directory of the user running the
    // program. If that directory does not exist, it is created, along
    // with its pol-chem-defs directory.

    // On MS-Windows sytems, the home directory is located at:

    // C:\Documents and Settings\username

    // On GNU/Linux and UNIX-based systems, the home directory is:

    // /home/username
        
    // Thus, respectively, the user has at its disposal the following
    // personal user data directories:

    // C:\Documents and Settings\username\.massxpert\pol-chem-defs

    // and

    // /home/username/.massxpert/pol-chem-defs

    
    // Get the absolute directory path to user's data directory.
    
    dir.setPath(QDir::homePath() + QDir::separator() + ".massxpert");
    
    // Now make some checks: if this directory does not exist, we have
    // to create it.
    if (!dir.exists())
      {
	if(!dir.mkpath(dir.absolutePath()))
	  {
	    qWarning() << __FILE__ << __LINE__ 
		       << "Directory" << dir.absolutePath()
		       << "does not exist, but its creation failed.";
	    
	    return false;
	  }
	else
	  {
// 	    qWarning() << __FILE__ << __LINE__ 
// 			<< "Creation of " 
// 			<< dir.absolutePath()
// 			<< "succeeded.";
	  }
      }
  
    m_userDataDir = dir.absolutePath();
  
    dir.setPath(m_userDataDir + QDir::separator() + "pol-chem-defs");
    
    if (!dir.exists())
      {
	if(!dir.mkpath(dir.absolutePath()))
	  {
	    qWarning() << __FILE__ << __LINE__ 
		       << "Directory" << dir.absolutePath()
		       << "does not exist, but its creation failed.";
	    
	    return false;
	  }
	else
	  {
// 	    qWarning() << __FILE__ << __LINE__ 
// 			<< "Creation of " 
// 			<< dir.absolutePath()
// 			<< "succeeded.";
	  }
      }
    
    m_userPolChemDefCatDir = dir.absolutePath();
    
    
    dir.setPath(m_userDataDir + QDir::separator() + "plugins");
  
    if (!dir.exists())
      {
	if(!dir.mkpath(dir.absolutePath()))
	  {
	    qWarning() << __FILE__ << __LINE__ 
		       << "Directory" << dir.absolutePath()
		       << "does not exist, but its creation failed.";
	    
	    return false;
	  }
	else
	  {
// 	    qWarning() << __FILE__ << __LINE__ 
// 			<< "Creation of " 
// 			<< dir.absolutePath()
// 			<< "succeeded.";
	  }
      }
     
    m_userPluginDir = dir.absolutePath();

    return true;
  }


  //! Sets the system data directory path.
  /*! Sets the system data directory path to the string passed
    as argument.
  
    \param config string holding the new system data directory
    path.
  */
  void 
  ConfigSettings::setSystemDataDir(const QString &config)
  {
    m_systemDataDir = config;
  }

  //! Returns the system data directory path.
  /*! 
  
    \return a constant reference to the system data directory
    member data.
  */
  const QString &
  ConfigSettings::systemDataDir() const
  {
    return m_systemDataDir;
  }


  //! Sets the system plugin directory path.
  /*! Sets the system plugin directory path to the string passed
    as argument.
  
    \param config string holding the new system plugin directory
    path.
  */
  void 
  ConfigSettings::setSystemPluginDir(const QString &config)
  {
    m_systemPluginDir = config;
  }

  //! Returns the system plugin directory path.
  /*! 
  
    \return a constant reference to the system plugin directory
    member data.
  */
  const QString &
  ConfigSettings::systemPluginDir() const
  {
    return m_systemPluginDir;
  }
				   
  
  void 
  ConfigSettings::setSystemLocalizationDir(const QString &config)
  {
    m_systemLocalizationDir = config;
  }
  
  
  const QString &
  ConfigSettings::systemLocalizationDir() const
  {
    return m_systemLocalizationDir;
  }
  

  //! Sets the user manual directory path.
  /*! Sets the user manual directory path to the string passed
    as argument.
  
    \param config string holding the new user manual directory
    path.
  */
  void 
  ConfigSettings::setUserManDir(const QString &config)
  {
    m_userManDir = config;
  }

  //! Returns the user manual directory path.
  /*! 
  
    \return a constant reference to the user manual directory
    member data.
  */
  const QString &
  ConfigSettings::userManDir() const
  {
    return m_userManDir;
  }

  
  //! Sets the user plugin directory path.
  /*! Sets the user plugin directory path to the string passed as
    argument.
  
    \param config string holding the new user plugin directory
    path.
  */
  void 
  ConfigSettings::setUserPluginDir(const QString &config)
  {
    m_userPluginDir = config;
  }


  //! Returns the user plugin directory path.
  /*! 
  
    \return a constant reference to the user plugin directory
    member data.
  */
  const QString &
  ConfigSettings::userPluginDir() const
  {
    return m_userPluginDir;
  }
  

  //! Sets the user data directory path.
  /*! Sets the user data directory path to the string passed as
    argument.
  
    \param config string holding the new user data directory
    path.
  */
  void 
  ConfigSettings::setUserDataDir(const QString &config)
  {
    m_userDataDir = config;
  }


  //! Returns the user configuration directory path.
  /*! 
  
    \return a constant reference to the user configuration directory
    member data.
  */
  const QString &
  ConfigSettings::userDataDir() const
  {
    return m_userDataDir;
  }
  

  //! Sets a system configuration directory path.
  /*! Sets the system configuration directory path where the polymer
    chemistry definition catalogues are stored.
  
    \param config string holding the configuration directory path.
  */
  void 
  ConfigSettings::setSystemPolChemDefCatDir(const QString &config)
  {
    m_systemPolChemDefCatDir = config;
  }


  //! Returns a configuration directory path.
  /*! Returns the system configuration directory path where the polymer
    chemistry definition catalogues are stored.

    \return a constant reference to the configuration directory member
    data.
  */
  const QString &
  ConfigSettings::systemPolChemDefCatDir() const
  {
    return m_systemPolChemDefCatDir;
  }

  
  //! Sets a user configuration directory path.
  /*! Sets the user configuration directory path where the polymer
    chemistry definition catalogues are stored.
  
    \param config string holding the configuration directory path.
  */
  void 
  ConfigSettings::setUserPolChemDefCatDir(const QString &config)
  {
    m_userPolChemDefCatDir = config;
  }


  //! Returns a configuration directory path.
  /*! Returns the user configuration directory path where the polymer
    chemistry definition catalogues are stored.

    \return a constant reference to the configuration directory member
    data.
  */
  const QString &
  ConfigSettings::userPolChemDefCatDir() const
  {
    return m_userPolChemDefCatDir;
  }
 
} // namespace massXpert
