/***************************** 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 "MvQPixmapCache.h"

#include <QImageReader>

#ifdef METVIEW
#include "Path.h"
#endif

MvQPixmapCache::MvQPixmapCache(QPixmap pix) :
    defaultPixmap_(pix),
    size_(16)
{
}

QPixmap MvQPixmapCache::pixmap(QString s)
{
    QMap<QString, QPixmap>::iterator it = pixmaps_.find(s);
    if (it != pixmaps_.end()) {
        return it.value();
    }
    else {
        QMap<QString, QString>::iterator itP = mvIconPaths_.find(s);
        if (itP != mvIconPaths_.end()) {
            QPixmap p = create(mvIconPath(itP.value()));
            pixmaps_.insert(itP.key(), p);
            return p;
        }
    }

    return defaultPixmap_;
}

void MvQPixmapCache::addMvIconPath(QString key, QString path)
{
    mvIconPaths_[key] = path;
}

QPixmap MvQPixmapCache::create(QString path)
{
    QImageReader imgR(path);
    imgR.setScaledSize(QSize(size_, size_));
    QImage img = imgR.read();
    return QPixmap::fromImage(img);
}

QString MvQPixmapCache::mvIconPath(QString def) const
{
#ifdef METVIEW
    Path p(def.toStdString());
    std::string fname          = p.name();
    std::string::size_type pos = fname.rfind(".icon");
    if (pos != std::string::npos) {
        fname = fname.substr(0, pos);
    }

    std::string s       = getenv("METVIEW_DIR_SHARE");
    std::string svgName = s + "/icons_mv5/" + fname + ".svg";

    Path psvg(s + "/icons_mv5/" + fname + ".svg");
    if (psvg.exists()) {
        return QString::fromStdString(psvg.str());
    }
    else {
        Path pxpm(s + "/icons_mv5/" + fname + ".xpm");
        if (pxpm.exists()) {
            return QString::fromStdString(pxpm.str());
        }
    }

    return QString();
#endif
    return QString();
}
