/*
 * Qt wrapper for libindicate
 *
 * Copyright 2009 Canonical Ltd.
 *
 * Authors:
 * - Aurélien Gâteau <aurelien.gateau@canonical.com>
 *
 * License: LGPL v2.1 or LGPL v3
 */
#ifndef QINDICATEDECODE_H
#define QINDICATEDECODE_H

// Qt
#include <QDateTime>
#include <QDebug>
#include <QImage>
#include <QString>
#include <QStringList>

namespace QIndicate
{

namespace Decode
{

QString stringFromValue(const QByteArray& value)
{
    return QString::fromUtf8(value);
}

bool boolFromValue(const QByteArray& value, bool defaultValue)
{
    if (value == "true") {
        return true;
    }
    if (value == "false") {
        return false;
    }
    return defaultValue;
}

int intFromValue(const QByteArray& _value, int defaultValue)
{
    bool ok;
    int value = _value.toInt(&ok);
    return ok ? value : defaultValue;
}

QImage imageFromValue(const QByteArray& value)
{
    QByteArray data = QByteArray::fromBase64(value);
    return QImage::fromData(data);
}

QDateTime dateTimeFromValue(const QByteArray& _value)
{
    if (_value.isEmpty()) {
        return QDateTime();
    }

    const QString value = QString::fromUtf8(_value);

    // The time is received as an ISO8601 string which looks like this:
    // "1970-01-01T16:29:26.705000Z"
    // or like this if ms is 0:
    // "1970-01-01T16:29:26Z"
    //
    // The ending "Z" indicates this is UTC time
    //
    // Unfortunately this does not match with Qt::ISODate, so we parse it
    // ourself

    // Split date and time
    QStringList tokens = value.split('T');
    if (tokens.count() != 2) {
        qWarning() << "Could not separate date and time from" << value;
        return QDateTime();
    }
    QString dateStr = tokens[0];
    QString timeStr = tokens[1];

    // Parse the date
    QDate date = QDate::fromString(dateStr, "yyyy-MM-dd");
    if (!date.isValid()) {
        qWarning () << "Could not extract date from" << value;
        return QDateTime();
    }

    // Parse the HMS part
    QTime time = QTime::fromString(timeStr.left(8), "hh:mm:ss");
    if (!time.isValid()) {
        qWarning() << "Could not extract time from" << value;
        return QDateTime();
    }

    // Parse the msec part, if any
    QString str = timeStr.section('.', 1);
    if (!str.isEmpty()) {
        bool ok;
        int msec = str.left(3).toInt(&ok);
        if (!ok) {
            qWarning() << "Invalid msec value in" << value;
            return QDateTime();
        }
        time = time.addMSecs(msec);
    }

    return QDateTime(date, time, Qt::UTC).toLocalTime();
}

} // namespace

} // namespace

#endif /* QINDICATEDECODE_H */

