/*
  Copyright ( C ) 2002 Rik Hemsley (  rikkus ) <rik@kde.org>
  Copyright ( C ) 2002 Benjamin Meyer <ben-devel@meyerhome.net>
  Copyright ( C ) 2002 Nadeem Hasan <nhasan@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (  at your option ) any later version.

  This library 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

#include <tdeio/job.h>
#include <kdebug.h>

#include "httplookup.h"

namespace KCDDB
{
  HTTPLookup::HTTPLookup()
    : Lookup(),
      block_( true ), state_( Idle ), result_( Success )
  {
  }

  HTTPLookup::~HTTPLookup()
  {
  }

    CDDB::Result
  HTTPLookup::sendQuery()
  {
    TQString cmd = TQString( "cddb query %1 %2" )
      .arg( trackOffsetListToId(), trackOffsetListToString() ) ;

    makeURL( cmd );
    Result result = fetchURL();

    return result;
  }

    CDDB::Result
  HTTPLookup::sendRead( const CDDBMatch & match )
  {
    category_  = match.first;
    TQString discid    = match.second;

    TQString cmd = TQString( "cddb read %1 %2" )
        .arg( category_, discid );

    makeURL( cmd );
    Result result = fetchURL();

    return result;
  }

    void
  HTTPLookup::initURL( const TQString & hostName, uint port )
  {
    cgiURL_.setProtocol( "http" );
    cgiURL_.setHost( hostName );
    cgiURL_.setPort( port );
    cgiURL_.setPath( "/~cddb/cddb.cgi" );

    return;
  }

    void
  HTTPLookup::makeURL( const TQString & cmd )
  {
    // The whole query has to constructed each time as the
    // CDDB CGI script expects the parameters in strict order

    cgiURL_.setQuery( TQString() );

    TQString hello = TQString("%1 %2 %3 %4")
        .arg(user_, localHostName_, clientName(), clientVersion());

    cgiURL_.addQueryItem( "cmd", cmd );
    cgiURL_.addQueryItem( "hello", hello );
    cgiURL_.addQueryItem( "proto", "6" );
  }

    void
  HTTPLookup::jobFinished()
  {
    TQStringList lineList = TQStringList::split( "\n", TQString::fromUtf8(data_, data_.size()) );
    TQStringList::ConstIterator it = lineList.begin();

    switch ( state_ )
    {
      case WaitingForQueryResponse:

        if ( it != lineList.end() )
        {
          TQString line( *it );

          result_ = parseQuery( line );

          switch ( result_ )
          {
            case Success:

              if ( !block_ )
                emit queryReady();
              break;

            case MultipleRecordFound:

              ++it;
              while ( it != lineList.end() )
              {
                TQString line( *it );

                if ( '.' == line[ 0 ] )
                {
                  result_ = Success;

                  if ( !block_ )
                    emit queryReady();
                  break;
                }

                parseExtraMatch( line );
                ++it;
              }

              break;

            case ServerError:
            case NoRecordFound:
              if ( !block_ )
                emit queryReady();

              return;
              break;

            default:

              break;
          }
          
        }

        break;

      case WaitingForReadResponse:

        {
          CDInfo info;

          if ( info.load( TQString::fromUtf8(data_,data_.size()) ) )
          {
            info.category = category_;
            cdInfoList_.append( info );
          }

          if ( !block_ )
            emit readReady();
        }

        return;

        break; 

      default:

        break;
    }

    result_ = Success;
  }
}

#include "httplookup.moc"