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

 Copyright 2018 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 "MvQStyleDb.h"

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

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

#include "mars.h"
#include "MvQPaletteDb.h"
#include "MvMiscelaneous.h"

MvQStyleDb* MvQStyleDb::instance_ = 0;

//==========================================
//
// MvQStyleDbItem
//
//==========================================

MvQStyleDbItem::MvQStyleDbItem(QString name) :
    name_(name)
{
}

bool MvQStyleDbItem::listMatch(QStringList lst, QString pattern, Qt::CaseSensitivity cs) const
{
    foreach (QString t, lst)
        if (t.contains(pattern, cs))
            return true;

    return false;
}


bool MvQStyleDbItem::keywordMatch(QString pattern, Qt::CaseSensitivity cs) const
{
    return listMatch(keywords_, pattern, cs);
}

bool MvQStyleDbItem::layerMatch(QString pattern, Qt::CaseSensitivity cs) const
{
    return listMatch(layers_, pattern, cs);
}

bool MvQStyleDbItem::colourMatch(QString pattern, Qt::CaseSensitivity cs) const
{
    return listMatch(colours_, pattern, cs);
}

QString MvQStyleDbItem::previewFile() const
{
    return QString::fromStdString(metview::stylePreviewDirFile(name_.toStdString() + ".png"));
}

QPixmap MvQStyleDbItem::makePixmapToWidth(QSize pixSize)
{
    QPixmap p(previewFile());
    p = p.scaledToWidth(pixSize.width(), Qt::SmoothTransformation);

    //p=p.scaled(pixSize,Qt::KeepAspectRatio,Qt::SmoothTransformation);

    QRect rect(0, 0, p.width() - 1, p.height() - 1);
    QPainter painter(&p);
    painter.setPen(QColor(140, 140, 140));
    painter.drawRect(rect);

    return p;
}

QPixmap MvQStyleDbItem::makePixmapToHeight(QSize pixSize)
{
    QPixmap p(previewFile());
    p = p.scaledToHeight(pixSize.height(), Qt::SmoothTransformation);

    //p=p.scaled(pixSize,Qt::KeepAspectRatio,Qt::SmoothTransformation);

    QRect rect(0, 0, p.width() - 1, p.height() - 1);
    QPainter painter(&p);
    painter.setPen(QColor(140, 140, 140));
    painter.drawRect(rect);

    return p;
}


void MvQStyleDbItem::paint(QPainter* painter, QRect rect)
{
    //Keep the height
    QPixmap p(previewFile());
    if (!p.isNull()) {
        p = p.scaledToHeight(rect.height(), Qt::SmoothTransformation);
    }

    //p=p.scaled(pixSize,Qt::KeepAspectRatio,Qt::SmoothTransformation);

    painter->drawPixmap(rect.topLeft(), p);
    painter->drawRect(QRect(rect.topLeft(), p.size()));
}

//==========================================
//
// MvQStyleDb
//
//==========================================

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

    return instance_;
}

MvQStyleDb::MvQStyleDb()
{
    load();
    loadMagicsDef();

    layers_.sort();
    colours_.sort();
    keywords_.sort();
    parameters_.sort();
}

void MvQStyleDb::load()
{
    std::string fName = metview::ecchartsDirFile("styles.json");

    QFile fIn(fName.c_str());
    if (!fIn.open(QIODevice::ReadOnly | QIODevice::Text)) {
        marslog(LOG_WARN, "MvQStyleDb::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();
        //qDebug() << name;
        MvQStyleDbItem* item = new MvQStyleDbItem(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 == "colours") {
                toStringList(itOb.value().toArray(), item->colours_, colours_);
            }
            else if (obName == "keywords") {
                toStringList(itOb.value().toArray(), item->keywords_, keywords_);
            }
            else if (obName == "layers") {
                toStringList(itOb.value().toArray(), item->layers_, layers_);
            }
        }

        items_ << item;
    }
}

void MvQStyleDb::loadMagicsDef()
{
    std::string fName = metview::magicsStylesEcmwfDirFile("styles.json");

    QFile fIn(fName.c_str());
    if (!fIn.open(QIODevice::ReadOnly | QIODevice::Text)) {
        marslog(LOG_WARN, "MvQStyleDb::loadMagicsDef() --> 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();
        if (MvQStyleDbItem* item = find(name.toStdString())) {
            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_description") {
                    item->description_ = itOb.value().toString();
                }
            }
        }
    }
}

void MvQStyleDb::collect(QStringList lst, QStringList& allLst) const
{
    foreach (QString s, lst) {
        if (!allLst.contains(s))
            allLst << s;
    }
}

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

void MvQStyleDb::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;
    }
}

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

int MvQStyleDb::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;
}

QStringList MvQStyleDb::names() const
{
    QStringList lst;
    for (int i = 0; i < items_.count(); i++) {
        lst << items_[i]->name();
    }

    lst.sort();
    return lst;
}
