/* -*- c++ -*-
*
* generichttpserver.h
*
* Copyright (C) 2004 Petter Stokke <ummo@hellokitty.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/

#ifndef __kmldonkey_generichttpserver_h__
#define __kmldonkey_generichttpserver_h__

#include <kextsock.h>
#include <qhttp.h>
#include <qcstring.h>

class GenericHTTPSession;

/**
 * @author Petter Stokke
 */
class GenericHTTPServer : public KExtendedSocket
{
    Q_OBJECT
public:
    GenericHTTPServer(const QString& listenAddress = "0.0.0.0", int listenPort = 80);

protected slots:
    void incomingConnection();

protected:
    virtual GenericHTTPSession* buildSession(KExtendedSocket* sock) = 0;

};

class GenericHTTPSession : public QObject
{
    Q_OBJECT
public:
    GenericHTTPSession(GenericHTTPServer* parent, KExtendedSocket* sock);
    ~GenericHTTPSession();

    void sendResponseHeader(const QString& contentType, Q_ULLONG contentLength);
    void sendData(const QByteArray& data);
    void sendData(const QString& data);
    void endRequest();
    void sendResponse(const QString& contentType, const QByteArray& response);
    void sendResponse(const QString& contentType, const QString& response);
    void httpError(int err, const QString& msg = QString::null);

    virtual bool processRequest(const QHttpRequestHeader& header, const QByteArray& payload);

protected slots:
    void readData();
    void socketClosed(int);

private:
    void processBuffer();
    void discardBuffer();
    void discardBuffer(uint len);
    
    GenericHTTPServer* m_parent;
    KExtendedSocket* m_sock;
    QByteArray m_inbuf;
    bool m_isHEAD;
};

#endif
