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

#include <QByteArray>
#include <QBuffer>
#include <QDateTime>

#include "Request.h"
#include "Path.h"
#include "IconObject.h"
#include "IconClass.h"
#include "PreviewPanel.h"
#include "MvQFileInfo.h"
#include "MvQIconProvider.h"
#include "MvQMethods.h"
#include "MvQTheme.h"

IconDescription* IconDescription::instance_ = nullptr;

//#define DEBUG_ICONDESCRIPTION__

//======================================================================
//
//  IconDescriptionMakerObserver
//
//======================================================================

IconDescriptionMakerObserver::IconDescriptionMakerObserver(IconObject* item, IconDescriptionPresenter* caller) :
    path_(item->path().str()),
    cls_(item->iconClass().name()),
    caller_(caller)
{
}

void IconDescriptionMakerObserver::start()
{
    Request r(cls_.c_str());
    r("PATH") = path_.c_str();
    callService("IconDescMaker", r);
}

void IconDescriptionMakerObserver::reply(const Request& r, int err)
{
    IconDescription::Instance()->notifyReply(r, err, path_, cls_, caller_);
}

//======================================================================
//
//  IconDescriptionCache
//
//======================================================================

void IconDescriptionCache::check() {
    while (data_.size() > maxNum_) {
        IconDescriptionCacheItem *item =  data_.front();
        data_.pop_front();
#ifdef DEBUG_ICONDESCRIPTION__
        std::cout << "IconDescriptionCache::check --> delete item=" << item->path_ << std::endl;
#endif
        delete item;
    }
}

void IconDescriptionCache::add(const std::string& path, QPixmap pix, QString text)
{
    auto item = new IconDescriptionCacheItem();
    data_.push_back(item);
    item->path_ = path;
    item->pix_ = pix;
    item->text_ = text;
    item->creationTime_ = QDateTime::currentDateTime().toTime_t();
    check();
#ifdef DEBUG_ICONDESCRIPTION__
    print();
#endif
}

IconDescriptionCacheItem* IconDescriptionCache::find(IconObject* item)
{
#ifdef DEBUG_ICONDESCRIPTION__
    std::cout << "IconDescriptionCache::find --> " <<  item->path().str() << std::endl;
#endif
    for(std::deque<IconDescriptionCacheItem*>::iterator it=data_.begin();  it != data_.end();) {
        if ((*it)->path_ == item->path().str()) {
            if ((*it)->creationTime_ > item->path().lastModified()) {
#ifdef DEBUG_ICONDESCRIPTION__
                std::cout << "  found cached item" << std::endl;
#endif
                return *it;
            } else {
                auto obj = *it;
                it=data_.erase(it);
                delete obj;
#ifdef DEBUG_ICONDESCRIPTION__
                std::cout << "  found cached item with older timestamp [-->delete]" << std::endl;
                print();
#endif
            }
        } else {
            ++it;
        }
    }
#ifdef DEBUG_ICONDESCRIPTION__
    std::cout << "  not found in cache" << std::endl;
#endif
    return nullptr;
}

void IconDescriptionCache::print()
{
    std::cout << "IconDescriptionCache --> num=" << data_.size() << std::endl;
    for (auto item: data_) {
        std::cout << "  (" << item->path_ << std::endl << "," <<
                     item->creationTime_ << ")" << std::endl;
    }
}

//======================================================================
//
//  IconDescription
//
//======================================================================

IconDescription::IconDescription()
{
    infoNameColour_       = MvQTheme::colour("icon_info", "name").name();
    infoTypeColour_       = MvQTheme::colour("icon_info", "type").name();
    infoSizeColour_       = MvQTheme::colour("icon_info", "size").name();
    infoTimeColour_       = MvQTheme::colour("icon_info", "time").name();
    infoLinkLabelColour_  = MvQTheme::colour("icon_info", "linkLabel").name();
    infoLinkTargetColour_ = MvQTheme::colour("icon_info", "linkTarget").name();

    localImageClasses_ << "PNG" << "JPG" << "SVG" << "GIF" << "TIFF";
    serviceClasses_ << "GRIB" << "BUFR" << "GEOPOINTS" << "PDF" << "PSFILE" <<
                    "GEOVIEW" << "MCOAST" << "MAPVIEW" << "PCOAST";
}

IconDescription* IconDescription::Instance()
{
    if(!instance_) {
        instance_ = new IconDescription();
    }
    return instance_;
}

QString IconDescription::info(IconObject* obj)
{
    if (obj) {
        //Icon name
        QString txt = "<b><font color=\"" + infoNameColour_ + "\">";

        if (obj->isLink()) {
            txt += "<i>";
        }

        txt += QString::fromStdString(obj->name());

        if (obj->isLink()) {
            txt += "</i>";
        }

        txt += "</font> ";

        //icon class
        txt += " <font color=\"" + infoTypeColour_ + "\">(" + QString::fromStdString(obj->editorClass().name()) + ") </font> ";

        //file size
        if (!obj->isFolder()) {
            txt += "<font color=\"" + infoSizeColour_ + "\">" + MvQFileInfo::formatSize(obj->path().sizeInBytes()) + " </font> ";
        }

        //date and tyme
        txt += " <font color=\"" + infoTimeColour_ + "\">" + formatFileDate(obj->path().lastModified()) + " </font> ";

        //symlink target
        if (obj->isLink()) {
            txt += "<font color=\"" + infoLinkLabelColour_ + "\"> link: </font> ";
            txt += "<font color=\"" + infoLinkTargetColour_ + "\"><i>" + QString::fromStdString(obj->path().symlinkTarget()) + " </i></font> ";
        }

        txt += "</b>";

        return txt;
    }

    return QString();
}

QString IconDescription::table(IconObject* obj)
{
    if (obj) {
        QString txt;
        //Icon name
        txt = "<b><font color=\"" + infoNameColour_ + "\">";

        if (obj->isLink()) {
            txt += "<i>";
        }

        txt += QString::fromStdString(obj->name());

        if (obj->isLink()) {
            txt += "</i>";
        }

        txt += "</font></b>"; //</table><br>";

        txt += "<hr>";
        txt += "<table>";

        //icon class
        txt += " <tr><td>Type:</td><td><font color=\"" + infoTypeColour_ + "\">" + QString::fromStdString(obj->editorClass().name()) + " </font></td></tr> ";

        //file size
        if (!obj->isFolder()) {
            txt += "<tr><td>Size:</td><td><font color=\"" + infoSizeColour_ + "\">" + MvQFileInfo::formatSize(obj->path().sizeInBytes()) + " </font> </td></tr>";
        }

        //date and time
        txt += "<tr><td>Modified:</td><td><font color=\"" + infoTimeColour_ + "\">" + formatFileDate(obj->path().lastModified()) + " </font> </td></tr>";

        txt += "<tr><td>Owner:</td><td>" + QString::fromStdString(obj->path().owner()) + "</td></tr>";
        txt += "<tr><td>Permissions:</td><td>" + QString::fromStdString(obj->path().permissions()) + "</td></tr>";

        //full path
        //txt += " <tr><td>Path:</td><td><font color=\"" + infoNameColour_ + "\">" + QString::fromStdString(obj->path().str()) + " </font></td></tr> ";

        //symlink target
        if (obj->isLink()) {
            txt += "<tr><td><font color=\"" + infoNameColour_ + "\"> Link: </font></td><td>";
            txt += "<font color=\"" + infoLinkTargetColour_ + "\"><i>" + QString::fromStdString(obj->path().symlinkTarget()) + " </i></font></td></tr>";
        }

        txt += "</table>";

        return txt;
    }

    return QString();
}

QString IconDescription::formatFileDate(time_t t) const
{
    QDateTime dt = QDateTime::fromTime_t(t);
    return dt.toString("yyyy-MM-dd hh:mm");
}

void IconDescription::getContents(IconObject* item, IconDescriptionPresenter* caller)
{
    if(!item) {
        return;
    }

    QString cls = QString::fromStdString(item->className());

    auto cacheItem = contentsCache_.find(item);
    if (cacheItem) {
        caller->setContents(item->path().str(), cacheItem->pix(), cacheItem->text());
        return;
    }

    if(localImageClasses_.contains(cls)) {
        std::string p = item->path().str();
        QPixmap pix(QString::fromStdString(p));
        caller->setContents(item->path().str(), pix);
    } else if (serviceClasses_.contains(cls)) {
        replyObserver_ = new IconDescriptionMakerObserver(item, caller);
        replyObserver_->start();
        caller->setContents(item->path().str(), "Generating preview ...");
    } else {
        caller->setContents(item->path().str(), MvQIconProvider::pixmap(item, 96));
    }
}

void IconDescription::notifyReply(const Request& r, int err, const std::string& path, const std::string& cls, IconDescriptionPresenter* caller)
{
#ifdef DEBUG_ICONDESCRIPTION__
    std::cout << "IconDescription::notifyReply -->" << std::endl;
    std::cout << "  path=" << path << std::endl;
    std::cout << "  request=" << std::endl;
    r.print();
#endif

    QPixmap pix;
    QString txt;
    if (const char* ch = r("TMP_IMAGE_PATH")) {
        pix = QPixmap(ch);
        std::string tmpPath(ch);
        Path pp(tmpPath);
        pp.remove();
    }
    
    if (const char* ch = r("TEXT")) {
        txt = QString(ch);
    }

    if (txt.isEmpty() && pix.isNull()) {
        pix =  MvQIconProvider::pixmap(cls, 96);
    }

    caller->setContents(path, pix, txt);
    contentsCache_.add(path, pix, txt);
}

