/***************************************************************************
**
**  This file is part of waran.
**
**  waran 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.
**
**  waran 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: 2011-11-23
**  Copyright: 2011-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#ifndef DAEMONLINK_H
#define DAEMONLINK_H

#include <QtNetwork>

#include <QGpCoreTools.h>

class Station;

class DaemonLink: public QObject
{
  Q_OBJECT
public:
  DaemonLink(Station * station);
  ~DaemonLink();

  unsigned int port() const {return _port;}
  void setPort(unsigned int p) {_port=p;}

  bool isAvailable();

  void send(const char * msg);
  void send(const char * buf, unsigned int len);

  void disconnectFromHost();
protected:
  Station * station() {return _station;}
  const Station * station() const {return _station;}

  virtual int bytesAvailable(const char * buffer, int bytesCount)=0;
  bool match(const char * buffer, int& bytesRead, int bytesCount, const char * string);
  int findMatch(const char * buffer, int& bytesRead, int bytesCount, const char * string);
  QByteArray readString(const char * buffer, int& bytesRead, int bytesCount, bool& ok);
  int readInteger(const char * buffer, int& bytesRead, int bytesCount, bool& ok);
  long int readLongInteger(const char * buffer, int& bytesRead, int bytesCount, bool& ok);
  double readDouble(const char * buffer, int& bytesRead, int bytesCount, bool& ok);
protected slots:
  virtual void connected();
private slots:
  void bytesAvailable();
  void hungUp();
  void connect();
signals:
  void stateChanged();
private:
  Station * _station;
  unsigned int _port;

  QTcpSocket _socket;
  QGpCoreTools::DynamicBuffer _buffer;
  QTimer _connectionTimer;
};

#endif // DAEMONLINK_H
