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

 Copyright 2022 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 "WsType.h"

#include <cassert>
#include <QDir>
#include <QList>

#include "ConfigLoader.h"
#include "MvIconClassCore.h"
#include "MvIconLanguage.h"
#include "MvRequest.h"
#include "MvMiscellaneous.h"
#include "MvLog.h"
#include "WmoWeatherSymbol.h"

#include "MvQMethods.h"
#include "MvQStreamOper.h"

std::vector<WsGroup*> WsGroup::items_;
std::vector<WsType*> WsType::items_;
std::map<std::string, MvIconClassCore*> WsType::cls_;
WsType* WsType::userImageAllItem_ = nullptr;
WsType* WsType::wmoAllItem_ = nullptr;
WsType::Mode WsType::mode_ = WsType::NoMode;
int WsType::defaultPixSize_ = 20;
static QColor defaultPixBgColor(Qt::transparent);

//=================================================================
//
// WsGroup
//
//=================================================================

WsGroup::WsGroup(const MvRequest& r)
{
    const char* verb = r.getVerb();
    Q_ASSERT(verb);
    Q_ASSERT(strcmp(verb, "item_group") == 0);

    if (const char* lCh = r("name")) {
        name_ = QString(lCh);
    }
    if (const char* lCh = r("label")) {
        label_ = QString(lCh);
    }
    if (const char* lCh = r("desc")) {
        desc_ = QString(lCh);
    }

    if (desc_.isEmpty()) {
        desc_ = label_;
    }

    assert(!name_.isEmpty());
    items_.emplace_back(this);
}

WsGroup::WsGroup(QString name, QString label, QString desc) :
    name_(name), label_(label), desc_(desc)
{
    if (desc_.isEmpty()) {
        desc_ = label_;
    }

    assert(!name_.isEmpty());
    items_.emplace_back(this);
}

//=================================================================
//
//  WsType
//
//=================================================================

void WsType::init(Mode mode)
{
    mode_ = mode;
    // we only load it once
    if (items_.empty()) {
        if (mode_ == DesktopMode) {
            load_system_feature_items();
        }
        else if (mode_ == PlotWindowMode) {
            load_system_feature_items();
            load_user_feature_items();
            load_wmo_symbols();
        }
    }
}

QPixmap WsType::defaultPixmap() const
{
    if (pix_.isNull()) {
        pix_ = pixmap(defaultPixSize_, defaultPixSize_, QColor(), QPen(defaultPixBgColor), QBrush(defaultPixBgColor));
    }
    return pix_;
}

void WsType::load_system_feature_items()
{
    // we only load it once
    if (!items_.empty())
        return;

    std::string symFile = metview::etcDirFile("WsItems");
    if (symFile.empty())
        return;

    MvRequest r;
    r.read(symFile.c_str());
    if (r) {
        do {
            const char* verb = r.getVerb();
            assert(verb);
            if (strcmp(verb, "item") == 0) {
                const char* name = r("name");
                const char* req = r("req");
                assert(name);
                assert(req);
                if (strcmp(name, "user_image") == 0) {
                    assert(userImageAllItem_ == nullptr);
                    userImageAllItem_ = new WsUserImageAllType(r);
                    if (mode_ == DesktopMode) {
                        items_.push_back(userImageAllItem_);
                    }
                }
                else if (strcmp(name, "wmo_symbol") == 0) {
                    assert(wmoAllItem_ == nullptr);
                    assert(strcmp(req, "WS_WMOSYMBOL") == 0);
                    wmoAllItem_ = new WsWmoAllType(r);
                    if (mode_ == DesktopMode) {
                        items_.push_back(wmoAllItem_);
                    }
                }
                else if (strcmp(req, "WS_HIGH") == 0 || strcmp(req, "WS_LOW") == 0) {
                    items_.push_back(new WsCharImageType(r));
                }
                else if (strcmp(req, "WS_STORM") == 0) {
                    items_.push_back(new WsSvgImageType(r));
                }
                else if (strcmp(req, "WS_IMAGE") == 0 || strcmp(req, "WS_MARKER") == 0 ||
                         strcmp(req, "WS_SHAPE") == 0) {
                    items_.push_back(new WsStandardMultiType(r));
                }
                else {
                    items_.push_back(new WsStandardType(r));
                }
            }
            else if (mode_ == PlotWindowMode && strcmp(verb, "item_group") == 0) {
                new WsGroup(r);
            }
        } while (r.advance());
    }

    assert(userImageAllItem_);
    assert(wmoAllItem_);
}

// load user defined images
void WsType::load_user_feature_items()
{
    assert(userImageAllItem_);
    assert(wmoAllItem_);

    // Get user feature items directory names
    static QList<QString> dirs = {QString::fromStdString(metview::localFeatureItemsImageDir()),
                                  QString::fromStdString(metview::extraFeatureItemsImageDir())};

    QList<QString> added;
    for (auto items_dir : dirs) {
        // Search directory to get all items (svg and png)
        if (items_dir.isEmpty()) {
            continue;
        }
        QDir dir(items_dir);
        if (!dir.exists() && !dir.mkpath(dir.absolutePath())) {
            MvLog().warn() << "Cannot not create directory for weather symbol user images =" << dir.absolutePath();
            continue;
        }

        dir.setNameFilters({"*.svg", "*.png"});
        QStringList fileList = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable);

        // Add items
        for (const auto& fileName : fileList) {
            QString name = fileName.left(fileName.lastIndexOf(".")).toLower();
            if (name.isEmpty()) {
                MvLog().warn() << MV_FN_INFO << " Invalid user defined weather symbol image fileName=" << fileName;
                continue;
            }
            else {
                if (!added.contains(fileName)) {
                    //                    MvLog().dbg() << MV_FN_INFO << " name=" << name;
                    items_.push_back(new WsUserImageSingleType(fileName, items_dir));
                    added << fileName;
                }
                else {
                    MvLog().warn() << MV_FN_INFO << " Cannot add user define weather symbol image=" << fileName << ". Name=" << name << " is already in use.";
                }
            }
        }
    }
}

void WsType::load_wmo_symbols()
{
    WmoWeatherSymbol::init();
    for (auto const& v : WmoWeatherSymbol::elems()) {
        items_.push_back(new WsWmoSingleType(v.second));
    }
}

WsType* WsType::find(QString reqVerb, QString name)
{
    for (auto it : items_) {
        if (it->reqVerb() == reqVerb && it->name() == name) {
            return it;
        }
    }
    return nullptr;
}

WsType* WsType::findByReq(const MvRequest& req)
{
    const char* chVerb = req.getVerb();
    if (chVerb) {
        QString verb(chVerb);

        if (mode_ == DesktopMode && verb == "WS_IMAGE") {
            assert(userImageAllItem_);
            return userImageAllItem_;
        }

        QString rType, uType;
        if (const char* tCh = req("TYPE")) {
            rType = QString(tCh);
            rType = rType.toLower();
            if (const char* uCh = req("NAME")) {
                uType = QString(uCh);
            }
        }

        //        MvLog().dbg() << MV_FN_INFO << " verb=" << verb << " rType=" << rType << " uType=" << uType;
        for (auto it : items_) {
            if (it->matchReq(verb, rType, uType)) {
                //                MvLog().dbg() << " it=" << it->name() << " " << it->reqVerb();
                return it;
            }
        }
    }
    return nullptr;
}

MvRequest WsType::expandRequest(const MvRequest& r, long flags)
{
    if (const char* ch = r.getVerb()) {
        std::string verb(ch);
        auto it = cls_.find(verb);
        if (it != cls_.end()) {
            return it->second->language().expand(r, flags);
        }
    }
    return {};
}

// ConfigLoader
void WsType::load(request* r)
{
    if (const char* ch = get_value(r, "class", 0)) {
        if (strncmp(ch, "WS_", 3) == 0) {
            cls_[std::string(ch)] = new MvIconClassCore(ch, r);
        }
    }
}

//=================================================================
//
//  WsStandardType
//
//=================================================================

WsStandardType::WsStandardType(const MvRequest& r)
{
    const char* verb = r.getVerb();
    assert(verb);
    assert(strcmp(verb, "item") == 0);

    if (const char* lCh = r("name")) {
        name_ = QString(lCh);
    }
    if (const char* lCh = r("label")) {
        label_ = QString(lCh);
    }
    if (const char* lCh = r("desc")) {
        desc_ = QString(lCh);
    }
    if (const char* lCh = r("icon")) {
        iconName_ = QString(lCh);
    }
    if (const char* lCh = r("gr_type")) {
        grItemType_ = QString(lCh);
    }
    if (const char* lCh = r("req")) {
        reqVerb_ = QString(lCh);
    }
    if (const char* lCh = r("json")) {
        geojsonType_ = QString(lCh);
    }
    if (const char* lCh = r("group")) {
        group_ = QString(lCh);
    }

    if (desc_.isEmpty()) {
        desc_ = label_;
    }

    //    MvLog().dbg() << "WS=" << name_ << reqVerb_;
    assert(!name_.isEmpty());
    assert(!grItemType_.isEmpty());
    assert(!geojsonType_.isEmpty());
    assert(!reqVerb_.isEmpty());
}

QPixmap WsStandardType::pixmap(int width, int height, QColor /*fg*/, QPen /*boxPen*/, QBrush boxBrush) const
{
    auto col = ((boxBrush.style() == Qt::NoBrush) ? QColor(Qt::transparent) : boxBrush.color());
    return MvQ::makePixmap(iconPath(), width, height, col);
}

QString WsStandardType::iconPath() const
{
    return QString::fromStdString(metview::systemFeatureItemsFile(iconName_.toStdString()));
}

bool WsStandardType::matchReq(QString verb, QString /*reqType*/, QString /*reqUserType*/) const
{
    return reqVerb() == verb;
}

//=================================================================
//
//  WsSvgImageType
//
//=================================================================

WsSvgImageType::WsSvgImageType(const MvRequest& r) :
    WsStandardMultiType(r)
{
    const char* verb = r.getVerb();
    assert(verb);
    assert(strcmp(verb, "item") == 0);

    if (const char* lCh = r("template_colour")) {
        svgTemplateColour_ = QString(lCh);
    }
}

QPixmap WsSvgImageType::pixmap(int width, int height, QColor fg, QPen /*boxPen*/, QBrush boxBrush) const
{
    auto col = ((boxBrush.style() == Qt::NoBrush) ? QColor(Qt::transparent) : boxBrush.color());
    if (!svgTemplateColour_.isEmpty() && fg.isValid()) {
        return MvQ::makePixmapFromSvgTemplate(iconPath(), width, height,
                                              fg, svgTemplateColour_, {}, {});
    }
    return MvQ::makePixmap(iconPath(), width, height, col);
}

//=================================================================
//
//  WsCharImageType
//
//=================================================================

WsCharImageType::WsCharImageType(const MvRequest& r) :
    WsStandardType(r)
{
    const char* verb = r.getVerb();
    assert(verb);
    assert(strcmp(verb, "item") == 0);

    if (const char* lCh = r("template_colour")) {
        svgTemplateColour_ = QString(lCh);
    }
    if (const char* lCh = r("template_char")) {
        svgTemplateChar_ = QString(lCh)[0];
    }
}

QPixmap WsCharImageType::pixmapWithChar(int width, int height, QColor fg, QChar ch) const
{
    auto col = QColor(Qt::transparent);
    QString templateTxt = ">" + QString(svgTemplateChar_) + "</tspan></text>";
    QString txt = ">" + QString(ch) + "</tspan></text>";
    //    MvLog().dbg() << MV_FN_INFO << "svgTemplateColour=" <<  svgTemplateColour_ <<
    //                     " svgTemplateChar=" << QString(svgTemplateChar_) << " fg=" << fg <<" txt=" << txt;

    if (!svgTemplateColour_.isEmpty() && fg.isValid()) {
        return MvQ::makePixmapFromSvgTemplate(iconPath(), width, height,
                                              fg, svgTemplateColour_, txt, templateTxt);
    }
    return MvQ::makePixmap(iconPath(), width, height, col);
}

//=================================================================
//
//  WsStandardMultiType
//
//=================================================================

void WsStandardMultiType::updateTypeInReq(MvRequest& r)
{
    r("TYPE") = name_.toStdString().c_str();
}

bool WsStandardMultiType::matchReq(QString verb, QString reqType, QString /*reqUserType*/) const
{
    return reqVerb() == verb && name_ == reqType;
}

//=================================================================
//
//  WsUserIconAllType
//
//=================================================================

QString WsUserImageAllType::nameFromRequest(const MvRequest& req) const
{
    if (const char* t = req("TYPE")) {
        QString rType(t);
        rType = rType.toLower();
        if (rType == "user") {
            if (const char* u = req("NAME")) {
                return {u};
            }
        }
    }
    return {};
}

//=================================================================
//
//  WsWmoAllType
//
//=================================================================

QString WsWmoAllType::nameFromRequest(const MvRequest& req) const
{
    if (const char* t = req("TYPE")) {
        QString rType(t);
        return rType.toLower();
    }
    return {};
}

//=================================================================
//
// WsUserIconSingleType
//
//=================================================================

WsUserImageSingleType::WsUserImageSingleType(QString iconName, QString iconDir) :
    iconName_(iconName),
    iconDir_(iconDir)
{
    name_ = iconName_.left(iconName_.lastIndexOf(".")).toLower();
    label_ = name_;
    assert(!name_.isEmpty());
    label_.replace(0, 1, name_[0].toUpper());
    desc_ = "<b>" + iconName_ + "</b> (user defined)";
    //    MvLog().dbg() << MV_FN_INFO << "iconName=" << iconName_ << " iconDir=" << iconDir_;
}

QString WsUserImageSingleType::name() const
{
    return iconName_;
}

QString WsUserImageSingleType::nameFromRequest(const MvRequest&) const
{
    return iconName_;
}

QString WsUserImageSingleType::grItemType() const
{
    return userImageAllItem_->grItemType();
}

QString WsUserImageSingleType::reqVerb() const
{
    return userImageAllItem_->reqVerb();
}

QString WsUserImageSingleType::geojsonType() const
{
    return userImageAllItem_->geojsonType();
}

QString WsUserImageSingleType::group() const
{
    return userImageAllItem_->group();
}

QPixmap WsUserImageSingleType::pixmap(int width, int height, QColor /*fg*/, QPen /*boxPen*/, QBrush boxBrush) const
{
    auto col = ((boxBrush.style() == Qt::NoBrush) ? QColor(Qt::transparent) : boxBrush.color());
    return MvQ::makePixmap(iconPath(), width, height, col);
}

QSize WsUserImageSingleType::sizeInPx() const
{
    auto img = QImage(iconPath());
    return img.size();
}

QString WsUserImageSingleType::iconPath() const
{
    return iconDir_ + "/" + iconName_;
}

void WsUserImageSingleType::updateTypeInReq(MvRequest& r)
{
    r("TYPE") = "USER";
    r("NAME") = name().toStdString().c_str();
}

bool WsUserImageSingleType::matchReq(QString verb, QString reqType, QString reqUserType) const
{
    return reqVerb() == verb && reqType.toLower() == "user" &&
           (reqUserType == name_ || reqUserType == iconName_);
}

//=================================================================
//
// WsWmoSingleType
//
//=================================================================

WsWmoSingleType::WsWmoSingleType(WmoWeatherSymbol* symbol) :
    symbol_(symbol)
{
}

QString WsWmoSingleType::name() const
{
    if (symbol_) {
        return QString::fromStdString(symbol_->name());
    }
    return {};
}

QString WsWmoSingleType::nameFromRequest(const MvRequest&) const
{
    return name();
}

QString WsWmoSingleType::label() const
{
    return name();
}

QString WsWmoSingleType::description() const
{
    if (symbol_) {
        return MvQ::formatBoldText(QString::fromStdString(symbol_->name())) + ":<br>" + QString::fromStdString(symbol_->title());
    }
    return {};
}

QString WsWmoSingleType::subGroup() const
{
    if (symbol_) {
        auto gr = symbol_->group();
        if (gr) {
            return QString::fromStdString(gr->name_);
        }
    }
    return {};
}

QString WsWmoSingleType::grItemType() const
{
    return wmoAllItem_->grItemType();
}

QString WsWmoSingleType::reqVerb() const
{
    return wmoAllItem_->reqVerb();
}

QString WsWmoSingleType::geojsonType() const
{
    return wmoAllItem_->geojsonType();
}

QString WsWmoSingleType::group() const
{
    return wmoAllItem_->group();
}

QPixmap WsWmoSingleType::defaultPixmap() const
{
    if (pix_.isNull()) {
        pix_ = pixmap(defaultPixSize_, defaultPixSize_, QColor(Qt::black), QPen(Qt::NoPen), QBrush(Qt::NoBrush));
    }
    return pix_;
}

QPixmap WsWmoSingleType::pixmap(int width, int height, QColor fg, QPen boxPen, QBrush boxBrush) const
{
    if (symbol_) {
        return symbol_->pixmap(width, height, fg, boxPen, boxBrush);
    }
    return {width, height};
}

void WsWmoSingleType::updateTypeInReq(MvRequest& r)
{
    r("TYPE") = name().toStdString().c_str();
}

bool WsWmoSingleType::matchReq(QString verb, QString reqType, QString /*reqUserType*/) const
{
    return reqVerb() == verb && name() == reqType;
}

static SimpleLoader<WsType> loadClasses("object", 0);
