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

 Copyright 2020 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 "WmoWeatherSymbol.h"
#include "MvMiscellaneous.h"

#include <QDebug>
#include <QFile>
#include <QPainter>
#include <QPixmap>
#include <QString>
#include <QTextStream>
#include <QSvgRenderer>

std::map<std::string, WmoWeatherSymbol*> WmoWeatherSymbol::elems_;
std::vector<WmoWeatherSymbolGroup*> WmoWeatherSymbol::groups_;
static std::string xmlHeader = R"(<?xml version='1.0' encoding='UTF-8'?>)";

void WmoWeatherSymbol::init()
{
    if (!elems_.empty())
        return;

    auto p = metview::appDefDirFile("wmo_symbols.svg");
    qDebug() << QString::fromStdString(p);

    QFile file(QString::fromStdString(p));
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    QString line = in.readLine();
    QString elem;
    QString name;
    QString title;
    WmoWeatherSymbolGroup* group = nullptr;
    bool groups                  = true;
    while (!line.isNull()) {
        line = line.simplified();
        if (!line.isEmpty()) {
            if (groups) {
                if (line.startsWith("</groups>"))
                    groups = false;
                else {
                    if (!line.startsWith("<groups>")) {
                        auto gr = line.split("=");
                        if (gr.count() == 2) {
                            groups_.push_back(new WmoWeatherSymbolGroup(gr[0].toStdString(), gr[1].toStdString()));
                            //qDebug() << "group" << gr[0] << gr[1];
                        }
                    }
                }
            }

            if (line.startsWith("N=")) {
                if (!name.isEmpty()) {
                    elems_[name.toStdString()] =
                        new WmoWeatherSymbol(name.toStdString(),
                                             title.toStdString(),
                                             group,
                                             elem.toStdString());
                    //                    qDebug() << "add" << name;
                    name.clear();
                    title.clear();
                    elem.clear();
                }
                name = line.mid(2);
            }
            else if (!name.isEmpty()) {
                if (line.startsWith("T=")) {
                    title = line.mid(2);
                }
                else if (line.startsWith("G=")) {
                    int idx = line.mid(2).toInt();
                    group   = nullptr;
                    if (idx >= 0 && idx < static_cast<int>(groups_.size())) {
                        group = groups_[idx];
                    }
                }
                else if (!name.isEmpty()) {
                    elem += "\n" + line;
                }
            }
        }
        line = in.readLine();
    }
    if (!name.isEmpty()) {
        elems_[name.toStdString()] =
            new WmoWeatherSymbol(
                name.toStdString(),
                title.toStdString(),
                group,
                elem.toStdString());
    }
}

WmoWeatherSymbol* WmoWeatherSymbol::find(const std::string& name)
{
    auto it = elems_.find(name);
    if (it != elems_.end()) {
        return it->second;
    }
    return nullptr;
}

QPixmap WmoWeatherSymbol::pixmap(int w, int h, QColor fgCol, QPen boxPen, QBrush boxBrush)
{
    QString hd = "<?xml version='1.0' encoding='UTF-8'?>";
    auto t     = QString::fromStdString(xmlHeader + "\n" + body_);

    if (fgCol.isValid() && fgCol != QColor(Qt::black)) {
        t = t.replace("#000000", fgCol.name());
    }

    QSvgRenderer r(t.toUtf8());
    QPixmap pix(w, h);
    if (boxBrush.style() == Qt::NoBrush) {
        pix.fill(Qt::transparent);
    }

    QPainter painter(&pix);
    auto rect = QRect(0, 0, w, h);
    if (boxBrush.style() != Qt::NoBrush) {
        painter.fillRect(rect, boxBrush);
    }
    if (boxPen.style() != Qt::NoPen) {
        painter.setPen(boxPen);
        painter.drawRect(rect);
        painter.setPen(Qt::NoPen);
    }

    r.render(&painter, rect);
    return pix;
}
