/***************************** 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 *************************************/


#include "MvQBufrDataModel.h"

#include "MvQBufrDataItem.h"

#include <QColor>
#include <QDebug>
#include <QJsonDocument>
#include <QFont>


MvQBufrDataModel::MvQBufrDataModel(QObject* parent) :
    QAbstractItemModel(parent),
    root_(nullptr),
    compressed_(false),
    subsetNumber_(-1)
{
}

MvQBufrDataModel::~MvQBufrDataModel()
{
    if (root_)
        delete root_;
}

void MvQBufrDataModel::clear()
{
    beginResetModel();
    compressed_ = false;
    subsetNumber_ = -1;
    if (root_) {
        delete root_;
        root_ = nullptr;
    }
    endResetModel();
}


bool MvQBufrDataModel::loadJson(const QByteArray& json, bool compressed, QString& err)
{
    QJsonDocument doc = QJsonDocument::fromJson(json);

    if (!doc.isNull()) {
        beginResetModel();
        compressed_ = compressed;
        if (compressed_)
            subsetNumber_ = 0;
        else
            subsetNumber_ = -1;

        if (root_)
            delete root_;

        root_ = MvQBufrDataItem::loadDump(doc, err);
        endResetModel();
        return (err.isEmpty()) ? true : false;
    }
    else {
        clear();
        err = "JSON dump is empty";
        return false;
    }

    return false;
}

void MvQBufrDataModel::setSubsetNumber(int subsetNumber)
{
    if (compressed_) {
        if (subsetNumber_ != subsetNumber) {
            subsetNumber_ = subsetNumber;
            emit dataChanged(QModelIndex(), QModelIndex());
        }
    }
}

bool MvQBufrDataModel::hasData() const
{
    return (root_ && root_->childCount() > 0);
}

int MvQBufrDataModel::rowCount(const QModelIndex& parent) const
{
    if (!root_)
        return 0;

    if (parent.column() > 0)
        return 0;

    if (!parent.isValid()) {
        return root_->childCount();
    }
    else if (MvQBufrDataItem* pItem = indexToItem(parent)) {
        return (pItem->isGroup()) ? pItem->childCount() : 0;
    }

    return 0;
}

int MvQBufrDataModel::columnCount(const QModelIndex& /*parent*/) const
{
    return 4;
}

QVariant MvQBufrDataModel::data(const QModelIndex& index, int role) const
{
    if (!root_ || !index.isValid())
        return {};

    MvQBufrDataItem* item = indexToItem(index);
    Q_ASSERT(item);

    /*    if(role == Qt::BackgroundRole)
    {
        if(item->isGroup())
            return containerBg;
        return QVariant();
    }
*/
    /*    else if(role == Qt::ForegroundRole)
    {
        if(item->isGroup())
            return containerFg;
        return QVariant();
    }
*/
    if (role == Qt::DisplayRole) {
        if (index.column() == 0) {
            if (item->isGroup())
                return item->title(subsetNumber_);
            return item->key();
        }
        else if (index.column() == 1) {
            if (!item->isGroup())
                return item->value(subsetNumber_);
            return {};
        }
        else if (index.column() == 2) {
            if (!item->isGroup())
                return item->data("units");
            return {};
        }
        else if (index.column() == 3) {
            if (!item->isGroup())
                return item->extra();
            return {};
        }
    }
    else if (role == Qt::ToolTipRole) {
        if (!item->isGroup()) {
            QString tp;
            QStringList keys;
            keys << "index"
                 << "code"
                 << "units"
                 << "scale"
                 << "reference"
                 << "width";
            foreach (QString key, keys) {
                QString atp = item->data(key);
                if (!atp.isEmpty()) {
                    if (!tp.isEmpty())
                        tp += "<br>";
                    tp += "<b>" + key + "</b>: " + atp;
                }
            }
            return tp;
        }
    }
    else if (role == Qt::FontRole) {
        /*if(item->isGroup())
          {
              QFont f;
              f.setBold(true);
              return f;
         }*/
        return {};
    }

    return {};
}

QVariant MvQBufrDataModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return {};

    if (orientation == Qt::Horizontal) {
        switch (section) {
            case 0:
                return tr("Key");
            case 1:
                return tr("Value");
            case 2:
                return tr("Units");
            case 3:
                return tr("Extra");
            default:
                return {};
        }
    }

    return {};
}

QModelIndex MvQBufrDataModel::index(int row, int column, const QModelIndex& parent) const
{
    if (MvQBufrDataItem* parentItem = indexToItem(parent)) {
        // qDebug() <<  "parentItem" << parentItem->key();

        if (MvQBufrDataItem* item = parentItem->childAt(row)) {
            return createIndex(row, column, item);
        }
        else {
            return {};
        }
    }

    return {};
}

QModelIndex MvQBufrDataModel::parent(const QModelIndex& index) const
{
    if (!index.isValid())
        return {};

    if (MvQBufrDataItem* ch = indexToItem(index)) {
        MvQBufrDataItem* p = ch->parent();
        if (p == root_) {
            return {};
        }

        return createIndex(p->indexInParent(), 0, p);
    }

    return {};
}


MvQBufrDataItem* MvQBufrDataModel::indexToItem(const QModelIndex& idx) const
{
    if (!idx.isValid())
        return root_;

    return static_cast<MvQBufrDataItem*>(idx.internalPointer());
}
