/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include <QStringList>
#include <QHash>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>

class MvQBufrDataItem
{
public:
    MvQBufrDataItem(MvQBufrDataItem* parent = 0);
    virtual ~MvQBufrDataItem();

    MvQBufrDataItem* childAt(int row);
    MvQBufrDataItem* parent() const { return parent_; }
    int childCount() const;
    int indexInParent() const;

    virtual QString title(int) const { return QString(); }
    QString data(QString key) const;
    QString key() const;
    QString value(int subset = -1) const { return getValue(subset, true); }
    QString rawValue(int subset = -1) const { return getValue(subset, false); }
    QString getValue(int subset, bool includeCount) const;
    QStringList valueArray() const { return valueArray_; }
    bool valueIsArray() const { return !valueArray_.isEmpty(); }
    QString extra();

    virtual bool isGroup() const { return false; }

    static MvQBufrDataItem* loadDump(QJsonDocument doc, QString& err);
    static void loadDump(const QJsonValue& value, MvQBufrDataItem* parent = 0);
    static void addItem(QJsonObject o, MvQBufrDataItem* parent);

protected:
    void addChild(MvQBufrDataItem* item);
    static QString beautify(QString val);
    static QString beautify(QStringList arrayVal);
    static QString toString(const QString& key, QJsonValue v);

    QString key_;
    QString value_;
    QHash<QString, QString> data_;
    QStringList valueArray_;

    QList<MvQBufrDataItem*> children_;
    MvQBufrDataItem* parent_;
};

class MvQBufrDataGroupItem : public MvQBufrDataItem
{
    friend class MvQBufrDataItem;

public:
    MvQBufrDataGroupItem(MvQBufrDataItem* parent = 0) :
        MvQBufrDataItem(parent) {}

    bool isGroup() const { return true; }
    QString title(int subset = -1) const;

protected:
    QString title_;
};
