/*******************************************************************************
**
** Filename   : util
** Created on : 03 April, 2005
** Copyright  : (c) 2005 Till Adam
** Email      : <adam@kde.org>
**
*******************************************************************************/

/*******************************************************************************
**
**   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.
**
**   It 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
**
**   In addition, as a special exception, the copyright holders give
**   permission to link the code of this program with any edition of
**   the Qt library by Trolltech AS, Norway (or with modified versions
**   of Qt that use the same license as Qt), and distribute linked
**   combinations including the two.  You must obey the GNU General
**   Public License in all respects for all of the code used other than
**   Qt.  If you modify this file, you may extend this exception to
**   your version of the file, but you are not obligated to do so.  If
**   you do not wish to do so, delete this exception statement from
**   your version.
**
*******************************************************************************/

#include "pimutil.h"

#include "imapresourcesettings.h"

#include <QFileDialog>
#include <QDesktopServices>
#include <KMessageBox>
#include <KLocalizedString>
#include <KEmailAddress>

#include <QTextStream>
#include <QWidget>
#include <QPointer>
#include <QUrlQuery>

#include <errno.h>

OrgKdeAkonadiImapSettingsInterface *PimCommon::Util::createImapSettingsInterface(const QString &ident)
{
    if (isImapResource(ident)) {
        return
            new OrgKdeAkonadiImapSettingsInterface(
            QLatin1String("org.freedesktop.Akonadi.Resource.") + ident, QStringLiteral("/Settings"), QDBusConnection::sessionBus());
    } else {
        return nullptr;
    }
}

void PimCommon::Util::saveTextAs(const QString &text, const QString &filter, QWidget *parent, const QUrl &url, const QString &caption)
{
    QPointer<QFileDialog> fdlg(new QFileDialog(parent, QString(), url.path(), filter));
    if (!caption.isEmpty()) {
        fdlg->setWindowTitle(caption);
    }
    fdlg->setAcceptMode(QFileDialog::AcceptSave);
    if (fdlg->exec() == QDialog::Accepted) {
        const QString fileName = fdlg->selectedFiles().at(0);
        if (!saveToFile(fileName, text)) {
            KMessageBox::error(parent,
                               i18n("Could not write the file %1:\n"
                                    "\"%2\" is the detailed error description.",
                                    fileName,
                                    QString::fromLocal8Bit(strerror(errno))),
                               i18n("Save File Error"));
        }
    }
    delete fdlg;
}

bool PimCommon::Util::saveToFile(const QString &filename, const QString &text)
{
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }
    QTextStream out(&file);
    out.setCodec("UTF-8");
    out << text;
    file.close();
    return true;
}

QString PimCommon::Util::loadToFile(const QString &filter, QWidget *parent, const QUrl &url, const QString &caption)
{
    QPointer<QFileDialog> fdlg(new QFileDialog(parent, QString(), url.path(), filter));
    if (!caption.isEmpty()) {
        fdlg->setWindowTitle(caption);
    }
    fdlg->setAcceptDrops(QFileDialog::AcceptOpen);
    QString result;
    if (fdlg->exec() == QDialog::Accepted) {
        const QString fileName = fdlg->selectedFiles().at(0);
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            KMessageBox::error(parent,
                               i18n("Could not read the file %1:\n"
                                    "\"%2\" is the detailed error description.",
                                    fileName,
                                    QString::fromLocal8Bit(strerror(errno))),
                               i18n("Load File Error"));
        } else {
            result = QString::fromUtf8(file.readAll());
            file.close();
        }
    }
    delete fdlg;
    return result;
}

bool PimCommon::Util::isImapResource(const QString &identifier)
{
    return identifier.startsWith(KOLAB_RESOURCE_IDENTIFIER)
           || identifier.startsWith(IMAP_RESOURCE_IDENTIFIER)
           || identifier.startsWith(GMAIL_RESOURCE_IDENTIFIER);
}

void PimCommon::Util::invokeHelp(const QString &docfile, const QString &anchor)
{
    if (!docfile.isEmpty()) {
        QUrl url;
        url = QUrl(QStringLiteral("help:/")).resolved(QUrl(docfile));
        if (!anchor.isEmpty()) {
            QUrlQuery query(url);
            query.addQueryItem(QStringLiteral("anchor"), anchor);
            url.setQuery(query);
        }
        // launch khelpcenter, or a browser for URIs not handled by khelpcenter
        QDesktopServices::openUrl(url);
    }
}

QStringList PimCommon::Util::generateEmailList(const QStringList &list)
{
    QString str;
    const int numberOfElement{
        list.count()
    };
    for (int i = 0; i < numberOfElement; i++) {
        QString tmpStr = list.at(i);
        if (!tmpStr.trimmed().isEmpty()) {
            if (!str.isEmpty()) {
                str.append(QLatin1String(", "));
            }
            str.append(tmpStr);
        }
    }
    const QStringList emails = KEmailAddress::splitAddressList(str);
    return emails;
}
