/***************************************************************************
 *   Copyright (C) 2004-2009 by Pere Constans
 *   constans@molspaces.com
 *   cb2Bib version 1.3.2. Licensed under the GNU GPL version 3.
 *   See the LICENSE file that comes with this distribution.
 ***************************************************************************/
#ifndef NETWORK_H
#define NETWORK_H

#include <QFile>
#include <QNetworkAccessManager>
#include <QObject>
#include <QProcess>
#include <QUrl>


/**
    cb2Bib Network file copy/move

    @author Pere Constans
*/
class network : public QObject
{

    Q_OBJECT

public:
    network(QObject* parento = 0);
    ~network();

    void getFile(const QString& orig, const QString& dest, const QString& action = "copy", QObject* receiver = 0,
                 const char* callback = 0, const bool overwrite = false);

    inline const QString destinationFilename() const
    {
        return _destination_filename;
    }

    inline const QString sourceFilename() const
    {
        return _source_filename;
    }

    inline const QString errorString() const
    {
        return _getfile_error_string;
    }


signals:
    void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
    void getFileDone(bool status, const QString& error);
    void proxyAuthenticationRequired(const QNetworkProxy& proxy, QAuthenticator* auth);


public slots:
    void cancelDownload();


private:
    QByteArray _url_query;
    QFile _destination_file;
    QNetworkAccessManager* _fetcher;
    QNetworkAccessManager::Operation _operation;
    QNetworkReply* _current_reply;
    QProcess* _fetcher_client;
    QString FmClientCopyArg;
    QString FmClientCopyBin;
    QString FmClientMoveArg;
    QString FmClientMoveBin;
    QString _destination_filename;
    QString _getfile_error_string;
    QString _source_filename;
    bool FmClient;
    bool _getfile_succeeded;
    bool _is_fetching;
    bool checkDestination();
    bool fetch(const QUrl& url);
    bool getFilePrivate(const QString& orig, const QString& dest, const QString& action);
    bool getFile_c2b(const QString& action, const QNetworkAccessManager::Operation op = QNetworkAccessManager::GetOperation);
    bool getFile_client(const QString& action);
    int _redirection_count;


private slots:
    void emit_getFileDone();
    void emit_getFileDone(bool status, const QString& error);
    void fetcherClientEnded(int exitCode, QProcess::ExitStatus exitStatus);
    void fetcherEnded();
    void fetcherReadyRead();
    void loadSettings();
    void logError();

};

#endif
