/*
  Copyright (c) 2013-2016 Montel Laurent <montel@kde.org>

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License, version 2, as
  published by the Free Software Foundation.

  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.,
  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "contactgrantleeprintobject.h"
#include "contactgrantleeprintaddressobject.h"
#include "contactgrantleeprintphoneobject.h"
#include "contactgrantleeprintimobject.h"
#include "contactgrantleeprintgeoobject.h"
#include "contactgrantleeprintcryptoobject.h"

#include <KContacts/PhoneNumber>

#include <QBuffer>
#include <QVariant>
#include <grantlee/metatype.h>
#include <QLocale>

using namespace KAddressBookGrantlee;

ContactGrantleePrintObject::ContactGrantleePrintObject(const KContacts::Addressee &address, QObject *parent)
    : QObject(parent),
      mAddress(address)
{
    const auto addresses = address.addresses();
    mListAddress.reserve(addresses.size());
    Q_FOREACH (const KContacts::Address &addr, addresses) {
        mListAddress << new ContactGrantleePrintAddressObject(addr);
    }

    const auto phoneNumbers = address.phoneNumbers();
    mListPhones.reserve(phoneNumbers.size());
    Q_FOREACH (const KContacts::PhoneNumber &phone, phoneNumbers) {
        mListPhones << new ContactGrantleePrintPhoneObject(phone);
    }
    const QStringList customs = mAddress.customs();
    if (!customs.empty()) {
        Q_FOREACH (const QString &custom, customs) {
            if (custom.startsWith(QStringLiteral("messaging/"))) {
                const int pos = custom.indexOf(QLatin1Char(':'));
                QString key = custom.left(pos);
                key.remove(QStringLiteral("-All"));
                const QString value = custom.mid(pos + 1);
                mListIm << new ContactGrantleePrintImObject(key, value);
            }
        }
    }
    mGeoObject = new ContactGrantleePrintGeoObject(address.geo());
    mCryptoObject = new ContactGrantleePrintCryptoObject(address);
}

ContactGrantleePrintObject::~ContactGrantleePrintObject()
{
    delete mGeoObject;
    qDeleteAll(mListAddress);
    qDeleteAll(mListPhones);
    qDeleteAll(mListIm);
    delete mCryptoObject;
}

QString ContactGrantleePrintObject::realName() const
{
    return mAddress.realName();
}

QString ContactGrantleePrintObject::formattedName() const
{
    return mAddress.formattedName();
}

QString ContactGrantleePrintObject::prefix() const
{
    return mAddress.prefix();
}

QString ContactGrantleePrintObject::givenName() const
{
    return mAddress.givenName();
}

QString ContactGrantleePrintObject::additionalName() const
{
    return mAddress.additionalName();
}

QString ContactGrantleePrintObject::familyName() const
{
    return mAddress.familyName();
}

QString ContactGrantleePrintObject::suffix() const
{
    return mAddress.suffix();
}

QString ContactGrantleePrintObject::nickName() const
{
    return mAddress.nickName();
}

QString ContactGrantleePrintObject::name() const
{
    return mAddress.name();
}

QString ContactGrantleePrintObject::languages() const
{
    QString result;
    QStringList langList;
    Q_FOREACH (const KContacts::Lang &lang, mAddress.langs()) {
        langList.append(lang.language());
    }
    if (!langList.isEmpty()) {
        result = langList.join(QStringLiteral(","));
    }
    return result;
}

QStringList ContactGrantleePrintObject::emails() const
{
    QStringList emails;
    Q_FOREACH (const QString &email, mAddress.emails()) {
        const QString fullEmail = QString::fromLatin1(QUrl::toPercentEncoding(mAddress.fullEmail(email)));

        const QString url = QStringLiteral("<a href=\"mailto:%1\">%2</a>")
                            .arg(fullEmail, email);
        emails << url;
    }
    return emails;
}

QString ContactGrantleePrintObject::organization() const
{
    return mAddress.organization();
}

QString ContactGrantleePrintObject::note() const
{
    return mAddress.note().replace(QLatin1Char('\n'), QStringLiteral("<br>"));
}

QString ContactGrantleePrintObject::webPage() const
{
    return mAddress.url().url().toDisplayString();
}

QString ContactGrantleePrintObject::webSite() const
{
    return webPage();
}

QString ContactGrantleePrintObject::title() const
{
    return mAddress.title();
}

QString ContactGrantleePrintObject::preferredEmail() const
{
    return mAddress.preferredEmail();
}

QString ContactGrantleePrintObject::role() const
{
    return mAddress.role();
}

QString ContactGrantleePrintObject::birthday() const
{
    return QLocale().toString(mAddress.birthday().date(), QLocale::LongFormat);
}

QString ContactGrantleePrintObject::department() const
{
    return mAddress.department();
}

QVariant ContactGrantleePrintObject::addresses() const
{
    return QVariant::fromValue(mListAddress);
}

QVariant ContactGrantleePrintObject::phones() const
{
    return QVariant::fromValue(mListPhones);
}

QVariant ContactGrantleePrintObject::instantManging() const
{
    return QVariant::fromValue(mListIm);
}

QVariant ContactGrantleePrintObject::geo() const
{
    return QVariant::fromValue(mGeoObject);
}

QVariant ContactGrantleePrintObject::crypto() const
{
    return QVariant::fromValue(mCryptoObject);
}

QString ContactGrantleePrintObject::addressBookName() const
{
    const QString addressBookName = mAddress.custom(QStringLiteral("KADDRESSBOOK"), QStringLiteral("AddressBook"));
    return addressBookName;
}

QString ContactGrantleePrintObject::photo() const
{
    if (mAddress.photo().isEmpty()) {
        return QString();
    } else {
        const QString photoStr = QStringLiteral("<img src=\"%1\" width=\"%2\" height=\"%3\"> &nbsp;")
                                 .arg(imgToDataUrl(mAddress.photo().data()), QString::number(60), QString::number(60));
        return photoStr;
    }
}

QString ContactGrantleePrintObject::imgToDataUrl(const QImage &image) const
{
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG");
    return QStringLiteral("data:image/%1;base64,%2").arg(QStringLiteral("PNG"), QString::fromLatin1(ba.toBase64()));
}

QString ContactGrantleePrintObject::logo() const
{
    if (mAddress.logo().isEmpty()) {
        return QString();
    } else {
        const QString photoStr = QStringLiteral("<img src=\"%1\" width=\"%2\" height=\"%3\"> &nbsp;")
                                 .arg(imgToDataUrl(mAddress.logo().data()), QString::number(60), QString::number(60));
        return photoStr;
    }
}

QString ContactGrantleePrintObject::anniversary() const
{
    const QDate anniversary = QDate::fromString(mAddress.custom(QStringLiteral("KADDRESSBOOK"),
                              QStringLiteral("X-Anniversary")), Qt::ISODate);
    if (anniversary.isValid()) {
        return (QLocale().toString(anniversary));
    }
    return QString();
}

QString ContactGrantleePrintObject::profession() const
{
    return mAddress.custom(QStringLiteral("KADDRESSBOOK"),
                           QStringLiteral("X-Profession"));
}

QString ContactGrantleePrintObject::office() const
{
    return mAddress.custom(QStringLiteral("KADDRESSBOOK"),
                           QStringLiteral("X-Office"));
}

QString ContactGrantleePrintObject::manager() const
{
    return mAddress.custom(QStringLiteral("KADDRESSBOOK"),
                           QStringLiteral("X-ManagersName"));
}

QString ContactGrantleePrintObject::assistant() const
{
    return mAddress.custom(QStringLiteral("KADDRESSBOOK"),
                           QStringLiteral("X-AssistantsName"));
}

QString ContactGrantleePrintObject::spouse() const
{
    return mAddress.custom(QStringLiteral("KADDRESSBOOK"),
                           QStringLiteral("X-SpousesName"));
}
