/*
   This file is part of the KDE project
   Copyright (C) 2003 Tobias Koenig <tokoe@kde.org>
                      Joseph Wenninger <jowenn@kde.org>
                      Ingo Kloecker <kloecker@kde.org>
   Copyright (C) 2004 Tobias Koenig <tokoe@kde.org>
                      Joseph Wenninger <jowenn@kde.org>
                      Ingo Kloecker <kloecker@kde.org>
                      Dirk Schmidt <fs@dirk-schmidt.net>
 
   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 <kdebug.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <tdeabc/distributionlist.h>
#include <tdeabc/stdaddressbook.h>

#include "KWMailMergeTDEABC.h"
#include "KWMailMergeTDEABCConfig.h"

KWMailMergeTDEABC::KWMailMergeTDEABC( TDEInstance *inst, TQObject *parent )
        : KWMailMergeDataSource( inst, parent )
{
    _addressBook = TDEABC::StdAddressBook::self();
    _iterator = _addressBook->begin();


    // init record list
    // Using names from kaddressbook.
    sampleRecord[ ("KAddressbook identifier") ] = TDEABC::Addressee::uidLabel();
    sampleRecord[ ("Name" ) ] = TDEABC::Addressee::nameLabel();
    sampleRecord[ ("Formatted name" ) ] = TDEABC::Addressee::formattedNameLabel();
    sampleRecord[ ("Family names" ) ] = TDEABC::Addressee::familyNameLabel();
    sampleRecord[ ("Given name" ) ] = TDEABC::Addressee::givenNameLabel();
    sampleRecord[ ("Additional names" ) ] = TDEABC::Addressee::additionalNameLabel();
    sampleRecord[ ("Honorific prefixes" ) ] = TDEABC::Addressee::prefixLabel();
    sampleRecord[ ("Honorific suffixes" ) ] = TDEABC::Addressee::suffixLabel();
    sampleRecord[ ("Nick name" ) ] = TDEABC::Addressee::nickNameLabel();
    sampleRecord[ ("Birthday" ) ] = TDEABC::Addressee::birthdayLabel();
    sampleRecord[ ("Home address: Street" ) ] = TDEABC::Addressee::homeAddressStreetLabel();
    sampleRecord[ ("Home address: Locality" ) ] = TDEABC::Addressee::homeAddressLocalityLabel();
    sampleRecord[ ("Home address: Region" ) ] = TDEABC::Addressee::homeAddressRegionLabel();
    sampleRecord[ ("Home address: Postal code" ) ] = TDEABC::Addressee::homeAddressPostalCodeLabel();
    sampleRecord[ ("Home address: Country" ) ] = TDEABC::Addressee::homeAddressCountryLabel();
    sampleRecord[ ("Home address: Label" ) ] = TDEABC::Addressee::homeAddressLabelLabel();
    sampleRecord[ ("Business address: Street" ) ] = TDEABC::Addressee::businessAddressStreetLabel();
    sampleRecord[ ("Business address: Locality" ) ] = TDEABC::Addressee::businessAddressLocalityLabel();
    sampleRecord[ ("Business address: Region" ) ] = TDEABC::Addressee::businessAddressRegionLabel();
    sampleRecord[ ("Business address: Postal code" ) ] = TDEABC::Addressee::businessAddressPostalCodeLabel();
    sampleRecord[ ("Business address: Country" ) ] = TDEABC::Addressee::businessAddressCountryLabel();
    sampleRecord[ ("Business address: Label" ) ] = TDEABC::Addressee::businessAddressLabelLabel();
    sampleRecord[ ("Home phone" ) ] = TDEABC::Addressee::homePhoneLabel();
    sampleRecord[ ("Business phone" ) ] = TDEABC::Addressee::businessPhoneLabel();
    sampleRecord[ ("Mobile phone" ) ] = TDEABC::Addressee::mobilePhoneLabel();
    sampleRecord[ ("Home fax" ) ] = TDEABC::Addressee::homeFaxLabel();
    sampleRecord[ ("Business fax" ) ] = TDEABC::Addressee::businessFaxLabel();
    sampleRecord[ ("Car phone" ) ] = TDEABC::Addressee::carPhoneLabel();
    sampleRecord[ ("ISDN" ) ] = TDEABC::Addressee::isdnLabel();
    sampleRecord[ ("Pager" ) ] = TDEABC::Addressee::pagerLabel();
    sampleRecord[ ("Email" ) ] = TDEABC::Addressee::emailLabel();
    sampleRecord[ ("Mailer" ) ] = TDEABC::Addressee::mailerLabel();
    sampleRecord[ ("Time zone" ) ] = TDEABC::Addressee::timeZoneLabel();
    sampleRecord[ ("Geographic position" ) ] = TDEABC::Addressee::geoLabel();
    sampleRecord[ ("Title" ) ] = TDEABC::Addressee::titleLabel();
    sampleRecord[ ("Role" ) ] = TDEABC::Addressee::roleLabel();
    sampleRecord[ ("Organization" ) ] = TDEABC::Addressee::organizationLabel();
    sampleRecord[ ("Note" ) ] = TDEABC::Addressee::noteLabel();
    sampleRecord[ ("productId" ) ] = TDEABC::Addressee::productIdLabel();
    sampleRecord[ ("Revision" ) ] = TDEABC::Addressee::revisionLabel();
    sampleRecord[ ("sortString" ) ] = TDEABC::Addressee::sortStringLabel();
    sampleRecord[ ("URL" ) ] = TDEABC::Addressee::urlLabel();
    sampleRecord[ ("Secrecy" ) ] = TDEABC::Addressee::secrecyLabel();
    sampleRecord[ ("Preferred address: Street" ) ] = TQString( "preferedAddressStreet" );
    sampleRecord[ ("Preferred address: Locality" ) ] = TQString( "preferedAddressLocality" );
    sampleRecord[ ("Preferred address: Region" ) ] = TQString( "preferedAddressRegion" );
    sampleRecord[ ("Preferred address: Postal code" ) ] = TQString( "preferedAddressPostalCode" );
    sampleRecord[ ("Preferred address: Country" ) ] = TQString( "preferedAddressCountry" );
    sampleRecord[ ("Preferred address: Label" ) ] = TQString( "preferedAddressLabel" );
}


KWMailMergeTDEABC::~KWMailMergeTDEABC()
{
    ;
}


void KWMailMergeTDEABC::addEntry( const TQString &uid )
{
    _individualUIDs.append( uid );
    makeUIDsExclusive();
}


void KWMailMergeTDEABC::addList( const TQString &id )
{
    _lists.append( id );
    parseList( id );
    makeUIDsExclusive();
}


void KWMailMergeTDEABC::clear()
{
    _exclusiveUIDs.clear();
    _individualUIDs.clear();
    _listUIDs.clear();
    _lists.clear();
}


int KWMailMergeTDEABC::getNumRecords() const
{
    kdDebug() << "KWMailMergeTDEABC::getNumRecords(): " << _exclusiveUIDs.count() << endl;
    return _exclusiveUIDs.count();
}


TQString KWMailMergeTDEABC::getValue( const TQString &name, int record ) const
{
    kdDebug() << "KWMailMergeTDEABC::getValue(" << name << ", " << record << ")" << endl;
    if ( record < 0 )
        return name;

    // This doesn't ever happen, right? So why is it there? Dirk Schmidt
    if ( record == -1 && _iterator == _addressBook->end() )
        return "";

    //
    // Set the iterator to the asked Addressee.
    //
    bool uidAvailable = false;
    if ( record != -1 )
    {
        int counter = 0;

        for ( _UIDIterator = _exclusiveUIDs.begin(); _UIDIterator != _exclusiveUIDs.end()
                && counter < record; _UIDIterator++ )
        {
            counter++;
        }

        for ( _iterator = _addressBook->begin(); _iterator != _addressBook->end(); ++_iterator )
        {

            if( _iterator->uid() == *_UIDIterator )
            {
                uidAvailable = true;
                break;
            }
        }
    }

    if( !uidAvailable )
    {
        return ( i18n ( "KAddressbook entry '%1' not available." ).arg( *_UIDIterator ) );
    }


    TDEABC::Addressee addr = *_iterator;
    _iterator++; // Don't know why. Could be removed? Dirk Schmidt


    //
    // Return the asked variable.
    //
    if ( name == "KAddressbook identifier" )
        return addr.uid();
    if ( name == "Name" )
        return addr.name();
    if ( name == "Formatted name" )
        return addr.formattedName();
    if ( name == "Family names" )
        return addr.familyName();
    if ( name == "Given name" )
        return addr.givenName();
    if ( name == "Additional names" )
        return addr.additionalName();
    if ( name == "Honorific prefixes" )
        return addr.prefix();
    if ( name == "Honorific suffixes" )
        return addr.suffix();
    if ( name == "Nick name" )
        return addr.nickName();
    if ( name == "Birthday" )
        return TDEGlobal::locale()->formatDate( addr.birthday().date() );

    if ( name == "Home address: Street" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Home );
        return a.street();
    }
    if ( name == "Home address: Locality" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Home );
        return a.locality();
    }
    if ( name == "Home address: Region" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Home );
        return a.region();
    }
    if ( name == "Home address: Postal code" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Home );
        return a.postalCode();
    }
    if ( name == "Home address: Country" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Home );
        return a.country();
    }
    if ( name == "Home address: Label" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Home );
        return a.label();
    }

    if ( name == "Business address: Street" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Work );
        return a.street();
    }
    if ( name == "Business address: Locality" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Work );
        return a.locality();
    }
    if ( name == "Business address: Region" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Work );
        return a.region();
    }
    if ( name == "Business address: Postal code" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Work );
        return a.postalCode();
    }
    if ( name == "Business address: Country" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Work );
        return a.country();
    }
    if ( name == "Business address: Label" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Work );
        return a.label();
    }

    if ( name == "Prefered address: Street" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Pref );
        return a.street();
    }

    if ( name == "Prefered address: Locality" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Pref );
        return a.locality();
    }
    if ( name == "Prefered address: Region" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Pref );
        return a.region();
    }
    if ( name == "Prefered address: Postal code" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Pref );
        return a.postalCode();
    }
    if ( name == "Prefered address: Country" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Pref );
        return a.country();
    }
    if ( name == "Prefered address: Label" )
    {
        TDEABC::Address a = addr.address( TDEABC::Address::Pref );
        return a.label();
    }

    if ( name == "Home phone" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Home );
        return phone.number();
    }
    if ( name == "Business phone" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Work );
        return phone.number();
    }
    if ( name == "Mobile phone" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Cell );
        return phone.number();
    }
    if ( name == "Home fax" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Home | TDEABC::PhoneNumber::Fax );
        return phone.number();
    }
    if ( name == "Business fax" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Work | TDEABC::PhoneNumber::Fax );
        return phone.number();
    }
    if ( name == "Car phone" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Car );
        return phone.number();
    }
    if ( name == "ISDN" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Isdn );
        return phone.number();
    }
    if ( name == "Pager" )
    {
        TDEABC::PhoneNumber phone = addr.phoneNumber( TDEABC::PhoneNumber::Pager );
        return phone.number();
    }

    if ( name == "Email" )
        return addr.preferredEmail();
    if ( name == "Mailer" )
        return addr.mailer();
    if ( name == "Time zone" )
    {
        TDEABC::TimeZone zone = addr.timeZone();
        return TQString::number( zone.offset() );
    }
    if ( name == "Geographic position" )
    {
        TDEABC::Geo geo = addr.geo();
        TQString lat;
        TQString longi;
        if(  geo.latitude()<0 )
            lat = TQString( i18n("%1 South") ).arg( -geo.latitude() );
        else
            lat = TQString( i18n("%1 North") ).arg( geo.latitude() );

        if(  geo.longitude()<0 )
            // There is something going wrong, because "W" is replaced by "q ".
            // Needs fix.
            longi = TQString( i18n("%1 West") ).arg( -geo.longitude() );
        else
            longi = TQString( i18n("%1 East") ).arg( geo.longitude() );

        return i18n( "Geographic coordinates", "%1, %2" ).arg ( lat, longi );
    }

    if ( name == "Title" )
        return addr.title();
    if ( name == "Role" )
        return addr.role();
    if ( name == "Organization" )
        return addr.organization();
    if ( name == "Note" )
        return addr.note();
    if ( name == "productId" )
        return addr.productId();
    if ( name == "Revision" )
        return TDEGlobal::locale()->formatDate( addr.revision().date() );
    if ( name == "sortString" )
        return addr.sortString();
    if ( name == "URL" )
        return addr.url().url();
    if ( name == "Secrecy" )
    {
        TDEABC::Secrecy secrecy = addr.secrecy();
        return TDEABC::Secrecy::typeLabel( secrecy.type() );
    }

    return ( i18n("Unkown mail merge variable: %1").arg ( name ) ) ;
}


TQStringList KWMailMergeTDEABC::lists() const
{
    return _lists;
}


void KWMailMergeTDEABC::load( TQDomElement& parentElem )
{
    clear();
    TQDomNode contentNode=parentElem.namedItem("CONTENT");
    if( contentNode.isNull() )
        return;
    for( TQDomNode rec=contentNode.firstChild(); !rec.isNull(); rec=rec.nextSibling() )
    {
        if( rec.nodeName()== "RECORD" )
        {
            for( TQDomElement recEnt=rec.firstChild().toElement(); !recEnt.isNull();
                    recEnt=recEnt.nextSibling().toElement() )
            {
                addEntry( recEnt.attribute( TQString::fromLatin1("uid") ) );
            }
        }
        else if( rec.nodeName() == "LIST" )
        {
            for( TQDomElement recEnt=rec.firstChild().toElement(); !recEnt.isNull();
                    recEnt=recEnt.nextSibling().toElement() )
            {
                addList( recEnt.attribute( TQString::fromLatin1("listid") ) );
            }
        }
        else
            kdDebug() << "rec.nodeName(): " << rec.nodeName() << endl;
    }
}


void KWMailMergeTDEABC::makeUIDsExclusive()
{
    _exclusiveUIDs = _individualUIDs + _listUIDs;
    _exclusiveUIDs.sort();
    kdDebug() << "KWMailMergeTDEABC::makeUIDsExclusive(): before: " << _exclusiveUIDs.join(",")
    << endl;
    TQString uid;
    for( TQStringList::Iterator it=_exclusiveUIDs.begin();
            it!=_exclusiveUIDs.end(); ++it )
    {
        if( *it == uid )
        {
            it = _exclusiveUIDs.remove( it );
        }
        uid = *it;
    }
    kdDebug() << "KWMailMergeTDEABC::makeUIDsExclusive(): after: " << _exclusiveUIDs.join(",")
    << endl;
}


void KWMailMergeTDEABC::parseList( const TQString& listName )
{
    if( listName.isEmpty() )
        return;

    kdDebug() << "KWMailMergeTDEABC::parseList: " << listName << endl;
    TDEABC::DistributionListManager dlm ( _addressBook );
    dlm.load();

    TQStringList::Iterator listIt;

    TDEABC::DistributionList* list = dlm.list( listName );
    TDEABC::DistributionList::Entry::List entries = list->entries();

    TDEABC::DistributionList::Entry::List::Iterator itemIt;
    for ( itemIt = entries.begin(); itemIt != entries.end(); ++itemIt )
    {
        kdDebug() << "WMailMergeTDEABC::parseList: Listentry UID: " <<
        (*itemIt).addressee.uid() << endl;
        _listUIDs.append( (*itemIt).addressee.uid() );
    }
}


void KWMailMergeTDEABC::refresh( bool )
{
    kdDebug() << "KWMailMergeTDEABC::refresh()" << endl;
    _iterator = _addressBook->begin();
    _UIDIterator = _individualUIDs.begin();

}


void KWMailMergeTDEABC::save( TQDomDocument& doc, TQDomElement& parent)
{
    TQDomElement cont=doc.createElement(TQString::fromLatin1("CONTENT"));
    parent.appendChild(cont);

    TQValueList<TQString>::ConstIterator it = _individualUIDs.begin();
    for( ; it != _individualUIDs.end(); ++it )
    {
        TQDomElement rec=doc.createElement(TQString::fromLatin1("RECORD"));
        cont.appendChild(rec);
        TQDomElement recEnt=doc.createElement(TQString::fromLatin1("ITEM"));
        recEnt.setAttribute(TQString::fromLatin1("uid"),*it);
        rec.appendChild(recEnt);
    }

    it = _lists.begin();
    for( ; !(it == _lists.end()); ++it )
    {
        TQDomElement rec=doc.createElement(TQString::fromLatin1("LIST"));
        cont.appendChild(rec);
        TQDomElement recEnt=doc.createElement(TQString::fromLatin1("ITEM"));
        recEnt.setAttribute(TQString::fromLatin1("listid"),*it);
        rec.appendChild(recEnt);
    }
}

bool KWMailMergeTDEABC::showConfigDialog( TQWidget* par, int action )
{
    bool ret=false;
    if (action == KWSLCreate )
    {
        clear();
    }

    //if (action==KWSLOpen)
    {
        KWMailMergeTDEABCConfig *dia=new KWMailMergeTDEABCConfig( par, this );

        ret=( dia->exec() == TQDialog::Accepted );
        kdDebug() << "KWMailMergeTDEABCConfig::Accepted " << ret << endl;
        delete dia;
    }
    refresh(false);

    return ret;
}


TQStringList KWMailMergeTDEABC::singleRecords() const
{
    return _individualUIDs;
}



extern "C"
{
    KWORD_MAILMERGE_EXPORT KWMailMergeDataSource *create_kwmailmerge_tdeabc( TDEInstance *inst, TQObject *parent )
    {
        return new KWMailMergeTDEABC( inst, parent );
    }
}




#include "KWMailMergeTDEABC.moc"


