/***************************** 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 <QtGlobal>
#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;
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
    item->creationTime_ = QDateTime::currentDateTime().toSecsSinceEpoch();
#else
    item->creationTime_ = QDateTime::currentDateTime().toTime_t();
#endif
    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 (auto 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()
{
    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 = "";

        bool brokenLink = obj->isBrokenLink();

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

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

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

        // icon class
        auto subCol = MvQTheme::subText();
        txt += " " + MvQ::formatText(QString::fromStdString(obj->iconClass().name()), subCol);

        // file size
        if (!obj->isFolder()) {
            auto accCol = MvQTheme::accentText();
            txt += " " + MvQ::formatText(MvQFileInfo::formatSize(obj->path().sizeInBytes()), accCol);
        }

        // date and time
        txt += " " + formatFileDate(obj->path().lastModified(brokenLink));

        // symlink target
        if (obj->isLink()) {
            txt += MvQ::formatText(" symlink: ", subCol) + " <i>";
            auto target = QString::fromStdString(obj->path().symlinkTarget());
            if (!obj->isBrokenLink()) {
                txt += target;
            }
            else {
                txt += MvQ::formatText(target + " (broken)",
                                       MvQTheme::colour("folderview", "broken_link"));
            }
            txt += " </i>";
        }
        //        if (obj->isLink()) {
        //            txt += MvQ::formatText(" link: ", subCol);
        //            txt += "<i>" + MvQ::formatText(QString::fromStdString(obj->path().symlinkTarget()), subCol) + "</i>";
        //        }
        return txt;
    }

    return {};
}

QString IconDescription::table(IconObject* obj, bool addFullPath)
{
    if (obj) {
        QString txt;
        auto subCol = MvQTheme::subText();

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

        txt += QString::fromStdString("<b>" + obj->name() + "</b>");

        bool brokenLink = obj->isBrokenLink();

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

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

        // icon class
        txt += "<tr>" + MvQ::formatTableTdText("Type:", subCol) + "<td>" +
               QString::fromStdString(obj->editorClass().name()) + "</td></tr> ";

        // file size
        if (!obj->isFolder()) {
            txt += "<tr>" + MvQ::formatTableTdText("Size:", subCol) + "<td>" +
                   MvQFileInfo::formatSize(obj->path().sizeInBytes()) + "</td></tr>";
        }

        // date and time
        auto modTime = obj->path().lastModified(brokenLink);
        txt += "<tr>" + MvQ::formatTableTdText("Modified:", subCol) + "<td>" +
               ((modTime != 0) ? formatFileDate(modTime) : "???") + "</td></tr>";

        txt += "<tr>" + MvQ::formatTableTdText("Owner:", subCol) + "<td>" +
               QString::fromStdString(obj->path().owner(brokenLink)) + "</td></tr>";

        txt += "<tr>" + MvQ::formatTableTdText("Permissions:", subCol) + "<td>" +
               QString::fromStdString(obj->path().permissions(brokenLink)) + "</td></tr>";

        if (addFullPath) {
            txt += "<tr>" + MvQ::formatTableTdText("Path:", subCol) + "<td>" +
                   QString::fromStdString(obj->path().str()) + "</td></tr>";
        }

        // symlink target
        if (obj->isLink()) {
            txt += "<tr>" + MvQ::formatTableTdText("Symlink:", subCol) + "<td><i>";
            auto target = QString::fromStdString(obj->path().symlinkTarget());
            if (!obj->isBrokenLink()) {
                txt += target;
            }
            else {
                txt += MvQ::formatText(target + " (broken)",
                                       MvQTheme::colour("folderview", "broken_link"));
            }
            txt += " </i></td></tr>";
        }

        txt += "</table>";
        return txt;
    }
    return {};
}

QString IconDescription::formatFileDate(time_t t) const
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
    QDateTime dt;
    dt.setSecsSinceEpoch(t);
#else
    QDateTime dt = QDateTime::fromTime_t(t);
#endif
    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);
}
