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

 Copyright 2014 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 "MvQPaletteDb.h"

#include <QDebug>
#include <QPainter>
#include <QLinearGradient>

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

#include "mars.h"
#include "MvQPalette.h"
#include "MvMiscellaneous.h"

MvQPaletteDb* MvQPaletteDb::instance_ = nullptr;

//==========================================
//
// MvQPaletteDbItem
//
//==========================================

void MvQPaletteDbItem::generateColLst()
{
    colLst_.clear();
    for (int i = 0; i < colNameLst_.count(); i++) {
        colLst_ << MvQPalette::magics(colNameLst_[i].toStdString());
    }
}

QPixmap MvQPaletteDbItem::makePixmap(QSize pixSize)
{
    QPixmap pix(pixSize);

    if (colLst_.count() == 1) {
        QRect rect(0, 0, pixSize.width(), pixSize.height());
        QPainter painter(&pix);
        MvQPalette::paintAlphaBg(&painter, rect);
        painter.fillRect(rect, colLst_[0]);
    }
    else if (colLst_.count() > 1) {
        QRect rect(0, 0, pixSize.width(), pixSize.height());
        QPainter painter(&pix);
        MvQPalette::paintAlphaBg(&painter, rect);

        float delta = static_cast<float>(rect.width()) / static_cast<float>(colLst_.count());
        for (int i = 0; i < colLst_.count(); i++) {
            QRectF r(rect.x() + i * delta, rect.y(), delta, rect.height());
            painter.fillRect(r, QBrush(colLst_[i]));
        }

        // border
        painter.setPen(QColor(100, 100, 100));
        painter.drawRect(rect.adjusted(0, 0, -1, -1));
    }

    return pix;
}

void MvQPaletteDbItem::paint(QPainter* painter, QRect rect)
{
    if (colLst_.count() == 1) {
        MvQPalette::paintAlphaBg(painter, rect);
        painter->fillRect(rect, colLst_[0]);
    }
    else if (colLst_.count() > 1) {
        MvQPalette::paintAlphaBg(painter, rect);
        float delta = static_cast<float>(rect.width()) / static_cast<float>(colLst_.count());

        for (int i = 0; i < colLst_.count(); i++) {
            QRectF r(rect.x() + i * delta, rect.y(), delta, rect.height());
            painter->fillRect(r, QBrush(colLst_[i]));
        }

        // border
        painter->setPen(QColor(100, 100, 100));
        painter->drawRect(rect);
    }
}

//==========================================
//
// MvQPaletteDb
//
//==========================================

MvQPaletteDb* MvQPaletteDb::instance()
{
    if (!instance_)
        instance_ = new MvQPaletteDb();

    return instance_;
}

MvQPaletteDb::MvQPaletteDb()
{
    load();
    origins_.sort();
    colours_.sort();
    ecStyles_.sort();
    keywords_.sort();
    parameters_.sort();
    std::sort(nLevels_.begin(), nLevels_.end());
}

void MvQPaletteDb::load()
{
    std::string fName = metview::magicsStylesDirFile("palettes.json");

    QFile fIn(fName.c_str());
    if (!fIn.open(QIODevice::ReadOnly | QIODevice::Text)) {
        marslog(LOG_WARN, "MvQPaletteDb::load--> Could not open json config file: %s", fName.c_str());
        return;
    }

    QByteArray json = fIn.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(json);

    // This document is an array of groups
    Q_ASSERT(doc.isObject());

    // Iterate through the ojects in a group
    const QJsonObject& jsonob = doc.object();
    for (QJsonObject::const_iterator it = jsonob.constBegin(); it != jsonob.constEnd(); it++) {
        QString name = it.key();
        auto* item = new MvQPaletteDbItem(name);

        Q_ASSERT(it.value().isObject());

        QJsonObject ob = it.value().toObject();
        for (QJsonObject::const_iterator itOb = ob.constBegin();
             itOb != ob.constEnd(); itOb++) {
            QString obName = itOb.key();
            if (obName == "contour_shade_colour_list") {
                toStringList(itOb.value().toArray(), item->colNameLst_);
                item->generateColLst();
            }
            else if (obName == "tags") {
                QJsonObject obTag = itOb.value().toObject();
                for (QJsonObject::const_iterator itTag = obTag.constBegin(); itTag != obTag.constEnd(); itTag++) {
                    QString tagName = itTag.key();
                    if (tagName == "colours") {
                        toStringList(itTag.value().toArray(), item->cols_, colours_);
                    }
                    else if (tagName == "eccharts_style") {
                        toStringList(itTag.value().toArray(), item->ecStyle_, ecStyles_);
                    }
                    else if (tagName == "keywords") {
                        toStringList(itTag.value().toArray(), item->keywords_, keywords_);
                    }
                    else if (tagName == "n_levels") {
                        item->nLevels_ = itTag.value().toString().toInt();
                        if (!nLevels_.contains(item->nLevels_))
                            nLevels_ << item->nLevels_;
                    }
                    else if (tagName == "origin") {
                        item->origin_ = itTag.value().toString();
                        if (!origins_.contains(item->origin_))
                            origins_ << item->origin_;
                    }
                    else if (tagName == "parameter") {
                        toStringList(itTag.value().toArray(), item->params_, parameters_);
                    }
                }
            }
        }

        items_ << item;
    }
}

void MvQPaletteDb::toStringList(const QJsonArray& chArr, QStringList& lst) const
{
    for (int j = 0; j < chArr.count(); j++) {
        QString s = chArr[j].toString();
        lst << s;
    }
}

void MvQPaletteDb::toStringList(const QJsonArray& chArr, QStringList& lst, QStringList& allLst) const
{
    for (int j = 0; j < chArr.count(); j++) {
        QString s = chArr[j].toString();
        lst << s;
        if (!allLst.contains(s))
            allLst << s;
    }
}

MvQPaletteDbItem* MvQPaletteDb::find(const std::string& name) const
{
    int idx = indexOf(name);
    return (idx != -1) ? items_[idx] : 0;
}

int MvQPaletteDb::indexOf(const std::string& name) const
{
    QString qn = QString::fromStdString(name);
    for (int i = 0; i < items_.count(); i++) {
        if (items_[i]->name() == qn)
            return i;
    }
    return -1;
}
