/***************************************************************************
**
**  This file is part of GeopsyLand.
**
**  GeopsyLand is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  GeopsyLand 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 Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2018-12-03
**  Copyright: 2018-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#ifndef MINIBASH_H
#define MINIBASH_H

#include <QGpCoreTools.h>

#include "Terminal.h"

class TerminalProcess;

class MiniBash : public QObject
{
  Q_OBJECT
public:
  MiniBash(Terminal * terminal);
  ~MiniBash();

  enum Status {Idle, Processing, WaitMoreData};

  Terminal * terminal() const {return _terminal;}

  void addPath(const QString& p) {_paths.append(p);}

  QStringList availableCommands() const;

  QStringList complete(const QString& text, QString& completion) const;
  void parse(const QString& text);
  Status status() const {return _status;}

  void putData(const QString& data) {_terminal->putData(data);}
  void putData(const QStringList& data) {_terminal->putData(data);}

  QString previousHistory();
  QString nextHistory();

  bool killCurrentProcess();

  static QString fromNativePath(const QString& p);
  static QString toNativePath(const QString& p);
signals:
  void processFinished();
private slots:
  void oneProcessFinished();
  void exit();
private:
  bool exec();
  bool parse();
  static bool skipDoubleQuoteString(const QChar *& ptr, QString& s);
  static bool skipSimpleQuoteString(const QChar *& ptr, QString& s);
  static QString lastWord(const QString& text, bool& firstWord);
  static int matchingCount(const QString& s1, const QString& s2, int maxCount);

  Terminal * _terminal;
  Status _status;
  QString _buffer;
  QList<TerminalProcess *> _processes;
  QStringList _paths;
  QStringList _builtInCommands;
  QStringList _history;
  int _currentHistoryIndex;
};

#endif // MINIBASH_H

