#include <qwidget.h>
#include <qlayout.h>
#include <qlistbox.h>
#include <qstring.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qtextcodec.h>
#include <stdlib.h>
#include "qtopiaaddressbookplugin.h"
#include "qtopiaaddressee.h"

QtopiaAddressBookPlugin::QtopiaAddressBookPlugin() : ref(0) {
  qDebug("DTMAddressBookPlugin::DTMAddressBookPlugin");
  QString command ="db2file address -r -c utf8 > /tmp/addressDTM.txt";
  system (  command.latin1() );
}

QtopiaAddressBookPlugin::~QtopiaAddressBookPlugin() {
}

KABC::Addressee::List QtopiaAddressBookPlugin::getAddressees() {
  
  qDebug("Start: DTMAddressBookPlugin::getAddressees");

  KABC::Addressee::List result;
  QString text;
  QString  fileName = "/tmp/addressDTM.txt"; 
  QFile file( fileName );
  if (!file.open( IO_ReadOnly ) ) {
      return result;
  } 
  QTextStream ts( &file );
  ts.setCodec( QTextCodec::codecForName("utf8") );
  text = ts.read();
  file.close();  

  QStringList templist;
  QString tempString;
  int start = 0;
  int len = text.length();
  int end = text.find ("\n",start)+1;
  bool ok = true;
  start = end;
  int lastStart1 = -1;
  int lastStart2 = -1;
  while ( start > 0 ) {
      //qDebug("while start %d ", start); 
      if ( lastStart1 == start )
          break;
      lastStart1 =start;
      templist.clear();
      ok = true;
      int iii = 0;
      while ( ok ) {
     
          // qDebug("while ok %d ", start);

          if ( lastStart2 == start )
              break;
          lastStart2 =start;
          tempString = getPart(  text, ok, start );
          //if ( ! tempString.isEmpty() )
          //qDebug("tempString %s %d",tempString.latin1(), iii);
          iii++;
          if ( start >= len || start == 0 ) {
              start = 0;
              ok = false;
          }
          if ( tempString.right(1) =="\n" )
              tempString = tempString.left( tempString.length()-1);
          //if ( ok ) 
          templist.append( tempString ); 
          //qDebug("%d ---%s---", templist.count(),tempString.latin1() );
      }
      result.append(QtopiaAddressee(templist)); 
      //qDebug("name %s ",templist[2].latin1() );
      //qDebug("name %s ",templist[4].latin1() );
      //qDebug("name %s ",templist[5].latin1() );
      //qDebug("name %s ",templist[40].latin1() );
  }
  
  
  qDebug("End: DTMAddressBookPlugin::getAddressees"); 
  
  return result;
}

QString QtopiaAddressBookPlugin::getPart( const QString& text , bool &ok, int &start )
{
  //qDebug("start %d ", start);
  
    QString retval ="";
    if ( text.at(start) == '"' ) {
        if ( text.mid( start,2) == "\"\"" && !( text.mid( start+2,1) == "\"")) {
            start = start +2; 
            if ( text.mid( start,1) == "," ) {
                start += 1;
            }
            retval = "";
            if ( text.mid( start,1) == "\n" ) {
                start += 1;
                ok = false; 
            }
            return retval;
        }
        int hk = start+1;
        hk = text.find ('"',hk);
        while ( text.at(hk+1) == '"' )
            hk = text.find ('"',hk+2);
        retval = text.mid( start+1, hk-start-1);
        start = hk+1;
        retval.replace( QRegExp("\"\""), "\""); 
        if ( text.mid( start,1) == "," ) {
            start += 1;
        }
        if ( text.mid( start,1) == "\n" ) {
            start += 1;
            ok = false; 
        }
        //qDebug("retval***%s*** ",retval.latin1() );
        return retval;

    } else {
        int nl = text.find ("\n",start);
        int kom = text.find (',',start);
        if ( kom < nl ) {
            // qDebug("kom < nl %d ", kom);
            retval = text.mid(start, kom-start);
            start = kom+1;
            return retval;
        } else {
            if ( nl == kom ) {
                // qDebug(" nl == kom ");
                start = 0;
                ok = false;
                return "0";
            }
            // qDebug(" nl < kom ", nl);
            retval = text.mid( start, nl-start);
            ok = false;
            start = nl+1;
            return retval;
        }
    }

}
QString QtopiaAddressBookPlugin::name() {
  return "DTM addressbook plugin";
}

QRESULT QtopiaAddressBookPlugin::queryInterface( const QUuid &uuid, QUnknownInterface **iface )
{
    *iface = 0;
    if ( uuid == IID_QUnknown )
      *iface = this;
    else if ( uuid == IID_KOAddressBookInterface )
      *iface = this;
    if ( *iface )
      (*iface)->addRef();
    return QS_OK;
}

Q_EXPORT_INTERFACE()
{
    Q_CREATE_INSTANCE( QtopiaAddressBookPlugin )
}