//
// C++ Interface: z3950connection
//
// Description:
//
//
// Author: Thach Nguyen <thach.nguyen@rmit.edu.au>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
// Based on Tellico

#ifndef Z3950CONNECTION_H
#define Z3950CONNECTION_H



#include <qthread.h>
#include <qevent.h>
#include <qdeepcopy.h>

#include <config.h>


#if HAVE_YAZ
extern "C"
{
#include <yaz/zoom.h>
#include <yaz/marcdisp.h>
}
#include <yazpp/zoom.h>
#endif

class Z3950Searcher;

/**
	@author Thach Nguyen <thach.nguyen@rmit.edu.au>
*/


class Z3950ResultFound : public QCustomEvent
{
public:
    Z3950ResultFound(const QString& s) : QCustomEvent(uid()), m_result(QDeepCopy<QString>(s)) {}
    const QString& result() const { return m_result; }

    static int uid() { return User + 11111; }

private:
    QString m_result;
};

class Z3950QueryResult : public QCustomEvent
{
public:
    Z3950QueryResult(unsigned int n) : QCustomEvent(uid()) { num = n; }
    const unsigned int result() const { return num; }

    static int uid() { return User + 22222; }

private:
    unsigned int num;
};

class Z3950ConnectionDone : public QCustomEvent
{
public:
    Z3950ConnectionDone() : QCustomEvent(uid()), m_type(-1) {}
    Z3950ConnectionDone(const QString& s, int t) : QCustomEvent(uid()), m_msg(QDeepCopy<QString>(s)), m_type(t) {}

    const QString& message() const { return m_msg; }
    int messageType() const { return m_type; }

    static int uid() { return User + 33333; }

private:
    QString m_msg;
    int m_type;
};

class Z3950Connection : public QThread
{
public:
    Z3950Connection(Z3950Searcher* searcher,
                    const QString& host,
                    uint port,
                    const QString& dbname,
                    const QString& sourceCharSet,
                    const QString& syntax,
                    const QString& esn);

    ~Z3950Connection();
    void setQuery(const QString& query);
    void setUserPassword(const QString& user, const QString& pword);
    void run();
    void retrieveRange(unsigned int min, unsigned int max);
    void abort() { m_aborted = true; }

private:
    bool makeConnection();
    static QCString iconv(const QCString& text, const QString& fromCharSet, const QString& toCharSet);
    static QString toXML(const QCString& marc, const QString& fromCharSet);
    QCString toCString(const QString& text);
    QString toString(const QCString& text);
    void done();
    void done(const QString& message, int type);

    bool m_connected;
    bool m_aborted;

    Z3950Searcher* m_searcher;
#if HAVE_YAZ
    ZOOM::connection *conn;
#endif
    QString m_host;
    uint m_port;
    QString m_dbname;
    QString m_user;
    QString m_password;
    QString m_sourceCharSet;
    QString m_syntax;
    QString m_pqn;
    QString m_esn;

    unsigned int startRange, endRange;
    bool m_waitingRetrieveRange;

};
#endif
