/***************************** 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 = nullptr);
    virtual ~MvQBufrDataItem();

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

    virtual QString title(int) const { return {}; }
    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 = nullptr);
    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 = nullptr) :
        MvQBufrDataItem(parent) {}

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

protected:
    QString title_;
};
