#include "kdeaccountsformat.h"

#include <tqcstring.h>
#include <tqfile.h>

#include <kabc/addressbook.h>
#include <kabc/addressee.h>
#include <kabc/resourcefile.h>

extern "C"
{
  KDE_EXPORT KABC::FormatPlugin *format()
  {
    return new KDEAccountsFormat();
  }
}

/**
 * Loads addresses of the kde-common/accounts file-> The format is
 * pfeiffer    Carsten Pfeiffer               pfeiffer@kde.org
 */

bool KDEAccountsFormat::loadAll( KABC::AddressBook *book,
                              KABC::Resource *resource,
                              TQFile *file )
{
    if ( !book || !file ) // eh?
        return false;

    TQString uuid = "KDEAccountsEntry.";
    int id = 0;

    TQByteArray array = file->readAll();
    file->close();

    TQByteArray::ConstIterator it = array.begin();
    TQByteArray::ConstIterator end = array.end();
    TQByteArray::ConstIterator startLine;
    TQString line;
    char eol = '\n';
    char delim = ' ';

    for ( ; it < end; it++ )
    {
        startLine = it;

        for ( ; it && it < end && *it != eol; it++ )
        { } // find eol

        uint length = it - startLine;
        line = TQString::fromUtf8( startLine, length ).simplifyWhiteSpace();

        TQString nickName;
        TQString name;
        TQString email;

        int firstSpace = line.find( delim );
        if ( firstSpace > 0 )
        {
            nickName = line.left( firstSpace );

            int lastSpace = line.findRev( delim );
            if ( lastSpace > firstSpace )
            {
                email = line.mid( lastSpace +1 );

                int start = firstSpace + 1;
                int length = lastSpace - start;
                name = line.mid( start, length );

                if ( !email.isEmpty() )
                {
                    KABC::Addressee address;
                    address.setNickName( nickName  );
                    address.setNameFromString( name );
                    address.setOrganization("KDE Project");
                    address.insertCategory("KDE Developer");
                    address.insertEmail( email  );
                    address.setUid( uuid + TQString::number( id++ ));

                    address.setResource( resource );
                    book->insertAddressee( address );
                }
            }
        }
    }

    return true;
}

