/***************************************************************************
 *   Copyright (C) 2007 by Anistratov Oleg                                 *
 *   ower@users.sourceforge.net                                            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2        *
 *   as published by the Free Software Foundation;                         *
 *                                                                         *
 *   This program 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.                          *
 *                                                                         *
 ***************************************************************************/

#ifndef SENDERTHREAD_H
#define SENDERTHREAD_H

#include <QThread>
#include <QUdpSocket>
#include <QTcpSocket>
#include <QTimer>

#include "largedatagramout.h"
#include "userinfo.h"

/**
	@author Anistratov Oleg <ower@users.sourceforge.net>
*/
class SenderThread : public QThread
{
  Q_OBJECT
  private:
    char*                 m_buffer;
    QAbstractSocket*      m_socket;
    QUdpSocket*           m_udp;
    QTcpSocket*           m_tcp;
    quint16               m_port;
    LargeDatagramOut**    m_datagrams;
    quint32               m_datagramsNum;
    quint32               m_datagramsMaxNum;
    QTimer*               m_timer;

  public:
    SenderThread(QObject *parent = 0);
    ~SenderThread();

    void    run();

    quint32 getValidID() const;
    bool    containID(quint32 ID) const;
    LargeDatagramOut* findDatagram(quint16 ID) const;

    void setPort(quint16 port){m_port = port;}

    void useTcp(QTcpSocket* s = 0){if(s)m_tcp = s; m_socket = m_tcp;}
    void useUdp(QUdpSocket* s = 0){if(s)m_udp = s; m_socket = m_udp;}
    int send(char*, int, const QHostAddress& = QHostAddress());

  public slots:
    void sending()
    {
      for(quint32 i = 0; i < m_datagramsNum; i++, usleep(1))
        m_datagrams[i]->sendNextFragment(m_socket, m_port, m_buffer);
    }

    void deleteDatagram(LargeDatagramOut* dtgrm);
    void slot_fragmentsRequest(char* dtgrm, quint32 dtgrm_len);
    void slot_acceptSending(quint16);
    void slot_cancelTask   (quint16);
    void addTask    (char* hdr, quint16 hdr_len, char* data, quint32 data_len, quint64, quint32 ID);
    void addFileTask(char* hdr, quint16 hdr_len, const QString & filename , quint64, quint32 ID);

  signals:
    void sendingCancelled(quint16);
    void sendingFinished (quint16);
};

#endif
