/***************************************************************************
**
**  This file is part of QGpCoreTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file 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 Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2007-05-14
**  Copyright: 2007-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include "AbstractParameters.h"
#include "Message.h"
#include "Trace.h"
#include "File.h"
#include "CoreApplication.h"

namespace QGpCoreTools {

  void AbstractParameters::KeywordMap::add(const QString& key, AbstractParameters * param, int index)
  {
    Keyword k;
    k.param=param;
    k.index=index;
    insert(key, k);
  }

  bool AbstractParameters::KeywordMap::setValue(const QString& key, const QString& value, const QString& unit) const
  {
    // For compatibility, support also space inside keywords
    QString cleanKey=key;
    cleanKey.replace(" ", "_");

    App::log(6, tr("Setting '%1 (%2)' with value '%3'\n").arg(cleanKey).arg(unit).arg(value));
    QMap<QString, Keyword>::const_iterator it;
    it=QMap<QString, Keyword>::find(cleanKey);
    if(it!=end()) {
      return it.value().param->setValue(it.value().index, value, unit, *this);
    } else {
      return false;
    }
  }

  QString  AbstractParameters::KeywordMap::key(const AbstractParameters * param, int index) const
  {
    for(const_iterator it=begin(); it!=end(); it++) {
      if(it->param==param && it->index==index) {
        return it.key();
      }
    }
    return QString();
  }

  inline AbstractParameters::ParameterValue::ParameterValue(const QString& key, const QString& value, const QString& unit)
  {
    _key=key;
    _value=value;
    _unit=unit;
  }

  inline AbstractParameters::ParameterValue::ParameterValue(const ParameterValue& o)
  {
    _key=o._key;
    _value=o._value;
    _unit=o._unit;
  }

  inline bool AbstractParameters::ParameterValue::set(const KeywordMap& map) const
  {
    return map.setValue(_key, _value, _unit);
  }

  /*!
    \class AbstractParameters AbstractParameters.h
    \brief Brief description of class still missing

    Full description of class still missing
  */

  AbstractParameters::AbstractParameters()
  {
    _version=PARAMETERS_VERSION;
    _values=nullptr;
  }

  AbstractParameters::AbstractParameters(const AbstractParameters& o)
  {
    _version=o._version;
    _values=nullptr;
  }

  AbstractParameters::~AbstractParameters()
  {
    delete _values;
  }

  void AbstractParameters::operator=(const AbstractParameters& o)
  {
    _version=o._version;
    _values=nullptr;
  }

  /*!
    \fn AbstractParameters::setVersion(int v)

    Reimplement in parent classes, always call also this function
  */

  /*!
    Do not call this function in re-implementations to avoid several
    'PARAMETERS VERSION' in file output. Called once directly by load().
  */
  void AbstractParameters::collectKeywords(PARAMETERS_COLLECTKEYWORDS_ARGS)
  {
    TRACE;
    keywords.add(prefix+"PARAMETERS_VERSION"+suffix, this, 0);
  }

  bool AbstractParameters::setValue(PARAMETERS_SETVALUE_ARGS)
  {
    TRACE;
    Q_UNUSED(unit)
    Q_UNUSED(keywords)
    switch(index) {
    case 0:
      _version=value.toInt();
      return true;
    default:
      break;
    }
    return false;
  }

  /*!
    Used in re-implemented classes to correctly map keyword indexes.
    Call this function in re-implementations.
  */
  int AbstractParameters::keywordCount(PARAMETERS_KEYWORDCOUNT_ARGS) const
  {
    return 1;
  }

  /*!
    Used to assert that all keywordCount() function return the correct numbers.
    Re-implement only if at least one parameter class is embedded.
  */
  int AbstractParameters::totalKeywordCount(PARAMETERS_KEYWORDCOUNT_ARGS) const
  {
    // PARAMETERS_VERSION must not be counted several times
    return keywordCount()-AbstractParameters::keywordCount();
  }

  /*!
    Do not call this function in re-implementations to avoid several
    'PARAMETERS VERSION' in file output. Called once directly by save().
  */
  QString AbstractParameters::toString(PARAMETERS_TOSTRING_ARGS_IMPL) const
  {
    TRACE;
    Q_UNUSED(prefix)
    Q_UNUSED(suffix)
    QString log;
    log+="# Version 0: all files generated with releases before 20170901 (default for input)\n";
    log+=prefix+"PARAMETERS_VERSION"+suffix+"="+QString::number(_version)+"\n";
    return log;
  }

  bool AbstractParameters::load(QString fileName, const QString& beginPattern,
                                const QString& endPattern)
  {
    TRACE;
    if(fileName.isEmpty()) {
      fileName=Message::getOpenFileName(tr("Loading parameters"),
                                        tr("Parameter file (*)"));
    }
    if(fileName.isEmpty()) {
      return false;
    } else {
      QFile f(fileName);
      if(f.open(QIODevice::ReadOnly)) {
        QTextStream s(&f);
        return load(s, beginPattern, endPattern);
      } else {
        Message::warning(MSG_ID, tr("Loading parameters"),
                         tr("Unable to open file '%1' for reading").arg(fileName), Message::cancel());
        return false;
      }
    }
  }

  bool AbstractParameters::load(QTextStream& s, const QString& beginPattern, const QString& endPattern)
  {
    TRACE;
    _version=0; // Earlier versions did not specify the 'PARAMETERS VERSION'
    KeywordMap * keywords=createKeywordMap();
    File::readUntilPattern(s, beginPattern);
    QString line;
    while(!s.atEnd()) {
      line=s.readLine();
      if(line.trimmed().left(1)=="#") {
        if(!endPattern.isEmpty() && line.contains(endPattern)) {
          delete keywords;
          return true;
        }
      } else {
        if(!parse(line, keywords)) {
          delete keywords;
          return false;
        }
      }
    }
    delete keywords;
    return true;
  }

  bool AbstractParameters::parse(const QString& line, const KeywordMap * keywords)
  {
    TRACE;
    QString keyword, unit, value;
    const QChar * ptrBegin=line.data();
    const QChar * ptrEnd=ptrBegin+line.count();
    const QChar * ptr=ptrBegin;
    KeywordMap * myOwnKeywords;
    if(!keywords) {
      myOwnKeywords=createKeywordMap();
      keywords=myOwnKeywords;
    } else {
      myOwnKeywords=nullptr;
    }
    while(ptr<ptrEnd) {
      switch(ptr->unicode()) {
      case '=':
        if(keyword.isEmpty()) { // no unit found
          keyword=QString(ptrBegin, static_cast<int>(ptr-ptrBegin)).trimmed();
        }
        value=QString(ptr+1, static_cast<int>(line.count()-(ptr-line.data()+1))).trimmed();
        // Store modified values
        if(!_values) {
          _values=new QVector<ParameterValue>;
        }
        _values->append(ParameterValue(keyword,value, unit));
        // Apply modification if keywords are provided
        if(keywords->setValue(keyword,value, unit)) {
          delete myOwnKeywords;
          return true;
        } else {
          Message::warning(MSG_ID,tr("Loading parameters"),
                           tr("Unknown keyword '%1' or error setting value '%2'").arg(keyword).arg(value), Message::cancel(), true);
          delete myOwnKeywords;
          return false;
        }
      case '(': // skip everything inside (), usefull if '=' is inside
        keyword=QString(ptrBegin, static_cast<int>(ptr-ptrBegin)).trimmed();
        ptr++;
        ptrBegin=ptr;
        while(ptr<ptrEnd) {
          if(ptr->unicode()==')') {
            unit=QString(ptrBegin, static_cast<int>(ptr-ptrBegin)).trimmed();
            break;
          }
          ptr++;
        }
        break;
      }
      ptr++;
    }
    delete myOwnKeywords;
    return false;
  }

  bool AbstractParameters::save(QString fileName) const
  {
    TRACE;
    if(fileName.isEmpty()) {
      fileName=Message::getSaveFileName(tr("Loading parameters"),
                                        tr("Parameter file (*)"));
    }
    if(fileName.isEmpty()) {
      return false;
    } else {
      QFile f(fileName);
      if(f.open(QIODevice::WriteOnly)) {
        QTextStream s(&f);
        s << AbstractParameters::toString(); // save version
        s << toString();
        return true;
      } else {
        Message::warning(MSG_ID, tr("Saving parameters"),
                             tr("Unable to open file '%s' for writing").arg(fileName), Message::cancel());
        return false;
      }
    }
  }

  /*!
    Warn user that he/she is using an obsolete keyword
  */
  void AbstractParameters::obsoleteKeyword(const KeywordMap& keywords, int index) const
  {
    TRACE;
    QString key=keywords.key(this, index+AbstractParameters::keywordCount());
    if(!key.isEmpty()) {
      App::log(tr("Obsolete keyword '%1'\n").arg(key) );
    } else {
      App::log(tr("Obsolete keyword with unknown name (index=%1)\n").arg(index) );
    }
  }

  AbstractParameters::KeywordMap * AbstractParameters::createKeywordMap()
  {
    KeywordMap * keywords=new KeywordMap;
    // Add 'PARAMETERS VERSION'
    AbstractParameters::collectKeywords(*keywords, QString(), QString());
    collectKeywords(*keywords, QString(), QString());
    // Internal check that keywordCount() is correct
    int total=totalKeywordCount()+AbstractParameters::keywordCount();
    if(keywords->count()!=total) {
      qWarning() << tr("Fix keywordCount: %1 instead of %2")
                       .arg(keywords->count())
                       .arg(total) << Qt::endl;
    }
    return keywords;
  }

  bool AbstractParameters::setValues(const AbstractParameters& o)
  {
    TRACE;
    if(o._values) {
      KeywordMap * keywords=createKeywordMap();
      int n=o._values->count();
      for(int i=0; i<n; i++) {
        const ParameterValue& v=o._values->at(i);
        if(!v.set(*keywords)) {
          delete keywords;
          return false;
        }
      }
      delete keywords;
    } else {
      *this=o;
    }
    return true;
  }

} // namespace QGpCoreTools
