/*
	This file implements kab's importing functions for
	Netscape Messagers' exported address books in .ldif-format.

 	(C) Copyright 2001 by Helge Deller <deller@gmx.de>

	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., 675 Mass Ave, Cambridge, MA 02139, USA.

   	$Revision: 1.4 $

	Description:
	This modules can import .ldif-files, which can be generated in
	Netscape by exporting the local address book to a file.


	TODO:		- streetaddress IS CRYPTED !!!
			- change existing entry instead of adding a new one
			- export kab's address book in .ldif-format

	Enhancements:   - Nickname		(user1)
			- xmozillausehtmlmail   (user1)
			- pagerphone		(user1)
			- xmozillaanyphone	(user2)
			- modifytimestamp

	This is a sample Netscape .ldif file: (Ok means: will be imported)
	--------------------------------------------------------
	modifytimestamp: 20010322011327Z	Ok
	cn: Helge Deller			Ok
	xmozillanickname: spitzname		Ok  user1
	mail: deller@gmx.de			Ok
	xmozillausehtmlmail: FALSE		Ok  user1
	givenname: Helge			Ok
	sn: Deller				Ok
	xmozillauseconferenceserver: 0
	o: firma				Ok
	locality: ort				Ok
	st: bundesland				Ok
	description: bemerkungen stehen hier	Ok
	title: titl				Ok
	streetaddress:: YWRkcjEJ		Ok (encrypted!)
	postalcode: postleitzahl		Ok
	countryname: land			Ok
	telephonenumber: dienstl.		Ok
	homephone: privat			Ok
	facsimiletelephonenumber: faxnr		Ok
	ou: abteilung				Ok
	pagerphone: piepser			Ok
	cellphone: handynr			Ok
	homeurl: url				Ok
	xmozillaanyphone: dienstl.		Ok
	objectclass: top			Ok
	objectclass: person			Ok
*/


#include <qtextstream.h>
#include <qfile.h>
#include <kabapi.h>
#include <kdebug.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include "kab_netscape_io.h"


Netscape_io::Netscape_io(KabAPI * _api, QWidget * parent):
KabAPI(parent)
{
    api = _api;
}


static bool StringStartsWith(QString & source, const char *part,
			     QString & remaining)
{
    int len = strlen(part);

    if (source.left(len) == part) {
	remaining = source.mid(len).simplifyWhiteSpace();
	return remaining.length() > 0;
    } else
	return false;
}

int Netscape_io::Netscape_ldif_Import()
{
    QString name;
    name = KFileDialog::getOpenFileName("::ldif",
					QString("*.ldif *.LDIF|") +
					i18n
					("Netscape Messenger addressbook export files (*.ldif)")
					+ "\n*|" + i18n("All files"), this,
					i18n
					("Import Netscape Messanger addressbook export files..."));

    if (name.isEmpty())
	return 0;

    QFile file(name);
    if (!file.exists() || !file.open(IO_ReadOnly)) {
	KMessageBox::information(this,
				 i18n("Unable to read the file %1.").
				 arg(name), i18n("Error"));
	return 0;
    }

    KabKey key;
    AddressBook::Entry * entry = NULL;
    AddressBook::Entry::Address * address = NULL;
    QString line, value, watermark;
    int no = 0;

    QTextStream t(&file);
    t.setEncoding(QTextStream::UnicodeUTF8);	/* Latin1 */

    watermark = i18n("Entry imported on %1 from '%2'")
	.arg(KGlobal::locale()->formatDate(QDate::currentDate(), true))
	.arg(name);

    while (!t.eof()) {
	line = t.readLine();
	/* loop until the first "dn:" value is found */
	if (t.eof() || !StringStartsWith(line, "dn:", value))
	    continue;

	/* create an empty entry */
	if (!entry)
	    entry = new AddressBook::Entry;
	if (!address)
	    address = new AddressBook::Entry::Address;
	address->headline = i18n("Main contact information");

	do {
	    line = t.readLine();
	    line.stripWhiteSpace();
	    if (line.isEmpty())
		break;

	    if (StringStartsWith(line, "objectclass:", value))	/* unused entries */
		continue;

	    if (StringStartsWith(line, "cn:", entry->fn))	/* formatted name */
		continue;

	    if (StringStartsWith(line, "givenname:", entry->firstname)) {
		int pos;
		pos = entry->firstname.find(' ');
		if (pos > 0) {	/* split name into first- and middlename */
		    entry->middlename = entry->firstname.mid(pos + 1);
		    entry->firstname.remove(pos, 255);
		}
		continue;
	    }

	    if (StringStartsWith(line, "sn:", entry->lastname))
		continue;

	    if (StringStartsWith(line, "mail:", value)) {
		entry->emails.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "homeurl:", value)) {
		entry->URLs.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "xmozillanickname:", value)) {
		entry->user1 += i18n("Nickname: %1").arg(value) + "\n";
		continue;
	    }

	    if (StringStartsWith(line, "xmozillausehtmlmail:", value)) {
		entry->user1 += ((value == "FALSE")
				 ? i18n("Mailformat: Text") :
				 i18n("Mailformat: HTML"))
		    + "\n";
		continue;
	    }

	    if (StringStartsWith(line, "modifytimestamp:", value)) {
		entry->user1 +=
		    i18n("Last modified: %1").arg(value) + "\n";
		continue;
	    }

	    if (StringStartsWith(line, "description:", entry->comment))
		continue;

	    if (StringStartsWith(line, "title:", entry->title))	/* or: rank ? */
		continue;

	    if (StringStartsWith(line, "telephonenumber:", value)) {
		entry->telephone.
		    append(QChar('0' + (int) AddressBook::Fixed - 1));
		entry->telephone.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "homephone:", value)) {
		entry->telephone.
		    append(QChar('0' + (int) AddressBook::Fixed - 1));
		entry->telephone.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "facsimiletelephonenumber:", value)) {
		entry->telephone.
		    append(QChar('0' + (int) AddressBook::Fax - 1));
		entry->telephone.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "pagerphone:", value)) {
		entry->telephone.
		    append(QChar('0' + (int) AddressBook::User1 - 1));
		entry->telephone.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "cellphone:", value)) {
		entry->telephone.
		    append(QChar('0' + (int) AddressBook::Mobile - 1));
		entry->telephone.append(value);
		continue;
	    }

	    if (StringStartsWith(line, "xmozillaanyphone:", value)) {
		entry->telephone.
		    append(QChar('0' + (int) AddressBook::User2 - 1));
		entry->telephone.append(value);
		continue;
	    }

	    /* Addresses */
	    if (StringStartsWith(line, "postalcode:", address->zip))
		continue;

	    if (StringStartsWith(line, "countryname:", address->country))
		continue;

	    if (StringStartsWith(line, "streetaddress:", address->address)) {
		/* FIXME: streetaddress could be encrypted !! */
		continue;
	    }

	    if (StringStartsWith(line, "locality:", address->town))
		continue;

	    if (StringStartsWith(line, "st:", address->state))
		continue;

	    if (StringStartsWith(line, "ou:", address->orgUnit))
		continue;

	    if (StringStartsWith(line, "o:", address->org))
		continue;

	} while (!t.eof());

	/* append this address to this entry */
	entry->addresses.push_front(*address);

	/* store a watermark */
	if (entry->user4.isEmpty())
	    entry->user4 = watermark;

	if (api->add(*entry, key, false) == AddressBook::NoError)
	    ++no;

	if (entry)
	    delete entry;
	entry = NULL;

	if (address)
	    delete address;
	address = NULL;
    }				/* while (!t.eof()) */
    file.close();

    if (no) {
	emit(setStatus(i18n("%1 addresses imported.").arg(no)));
    } else {
	emit(setStatus(i18n("No addresses imported.")));
    }

    return no;
}

/*
int Netscape_io::Netscape_ldif_Export()
{
    // TODO:
    KMessageBox::information(this,
			     i18n("Not yet implemented !"), i18n("Error"));
    return 0;
}
*/
#include "kab_netscape_io.moc"
