#ifndef QGGRIFOBEAMUPTFTP_H
#define QGGRIFOBEAMUPTFTP_H

#include <QObject>

#include <QHostAddress>

class TftpReceiver
{
public:
    TftpReceiver(void* store, unsigned int size):
        buffer(reinterpret_cast<char*>(store)),
        max_size(size)
    {
    }

    virtual ~TftpReceiver() {}

    virtual bool receiveBegin(unsigned int expected_size)
    {
        if (expected_size>max_size)
            return false;
        return true;
    }

    virtual bool receiveError(unsigned int /*error*/)
    {
        return true;
    }

    virtual bool receiveBlock(const void* data, unsigned int len, unsigned /*lock_num*/)
    {
        memcpy(&buffer[used_size], data, len);
        used_size+=len;
        return true;
    }

    virtual bool receiveTerminated()
    {
        return true;
    }

protected:
    char* buffer;
    unsigned int max_size;
    unsigned int used_size;
};

class FpgaBridgeTftp : public QObject
{
    Q_OBJECT
public:
    explicit FpgaBridgeTftp(QObject *parent = 0);
    virtual ~FpgaBridgeTftp();

    void bind(const QHostAddress&adr);

    void bindRemote(const QHostAddress&adr, unsigned int dst_port=0);

    bool sendFile(const QString& localFileName, const QString& remoteFileName);
    bool sendMemory(void* data, unsigned int size, const char* remoteFileName);

    bool receive(TftpReceiver* theReceived, const QString& remoteFilename);

    bool receiveMemory(void* data, unsigned int max_size, const char* remoteFileName);

    //bool srioSend(unsigned int remote_address, unsigned int db, const void* data, unsigned int size);
    //bool srioReceive(unsigned int remote_address, unsigned int db, const void* data, unsigned int size);

    QString errorString();
    int errorCode();

    void setTargetNetIp(unsigned int ip);

signals:
    void serverHello(unsigned intip, int port, const QString& msg);

    void transferError(int code, const QString& msg);
    void progressInfo(int percentage, const QString& msg);

    void sendBegin();
    void sendTerminated();

    void sendStart();
    void sendError();

    void sendProgress(int completition);

    void receiveTerminated(int ok, QHostAddress remoteAddress);

    void queueChanged(int n);

public slots:
    void pingServer(int port);
    //void pingPartition(unsigned int address, int port);

private:
    class Implementation;
    Implementation& p_;
};

#endif // QGGRIFOBEAMUPTFTP_H
