//
// C++ Interface: sciencedirectsearcher
//
// Description: 
//
//
// Author: Thach Nguyen <thach.nguyen@rmit.edu.au>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef SCIENCEDIRECTSEARCHER_H
#define SCIENCEDIRECTSEARCHER_H

#include "searcher.h"
#include "searcherconfigwidget.h"

#include <kurl.h>
#include <kio/job.h>
#include <kconfig.h>

#include <qcstring.h> // for QByteArray
#include <qguardedptr.h>

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


class ScienceDirectSearcher;

class ScienceDirectConfigWidget : public SearcherConfigWidget {
	public:
		ScienceDirectConfigWidget(QWidget* parent, ScienceDirectSearcher* searcher = 0);
		virtual void updateSearcher() {};
};

class ScienceDirectSearcher : public searcher
{
Q_OBJECT
	public:
		ScienceDirectSearcher(QObject* parent, const char* name=0);
		
		virtual ~ScienceDirectSearcher();

		virtual QString source() const;
		virtual void setSource(const QString );
		virtual QString helpURL() {return QString::fromLatin1("http://www.sciencedirect.com")  ; }
		virtual bool isSearching() const { return m_started; }
		virtual void search(SearchKey key1, SearchKey key2, SearchKey key3 , const QString& value1, const QString& value2, const QString& value3, int operator1, int operator2);
		virtual void search(QString queryString);
		virtual void stop();
		virtual Type type() const { return ScienceDirect; }
		virtual void readConfig(KConfig* config, const QString& group);
		virtual void saveConfig(KConfig* config);
		virtual SearcherConfigWidget* configWidget(QWidget* parent);
		
		friend class ScienceDirectConfigWidget;
		virtual bool isWaitingRetrieveRange() const { return m_waitingRetrieveRange; }
		virtual void retrieveRange(unsigned int min, unsigned int max);
		virtual QStringList searchKey();
		virtual int maxSearchTerms() {return 100; }
		virtual bool allowAdvancedSearch() { return true; }
		static QString defaultName();

	private slots:
		void slotData(KIO::Job* job, const QByteArray& data);
		void slotComplete(KIO::Job* job);

	private:
		QString searchField(SearchKey key, QString data);
		QString boolOperator(int n);
		void httpRequest(QString args);
		void processStartPage();
		void processAdvancedSearchPage();
		void processExpertSearchPage();
		void searchResults();
		void fetchResults();
		void fetchBibtex();

		enum Step {
			Begin,
			StartPage,
			AdvancedSearchPage,
			ExpertSearchPage,
			Search,
			Wait,
			Fetch,
			FetchBibtex
		};

		KURL m_url;
		QByteArray m_data;
		QString m_query;
		int m_start;
		int m_end;
		int m_total;
		QString m_queryKey;
		QGuardedPtr<KIO::TransferJob> m_job;
		Step m_step;
		bool m_started;
		int retrieved;
		QString m_account;
		QString m_md5;
		QString m_articleListID;
		QString m_userID;
};

#endif
