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

#include <QPainter>
#include <QPixmap>
#include <QStyleOption>

#include "IconDescription.h"
#include "IconObject.h"
#include "MvQMethods.h"
#include "MvQTheme.h"

#include "ui_PreviewPanel.h"

PreviewPanel::PreviewPanel(QWidget* parent) :
    QWidget(parent),
    ui_(new Ui::PreviewPanel)
{
    ui_->setupUi(this);

    cssStyle_ = "<style>" + MvQTheme::htmlTableCss() + "</style>";
    connect(ui_->closeTb, SIGNAL(clicked()),
            this, SIGNAL(closePanel()));
}

void PreviewPanel::clear()
{
    ui_->contentsLabel->clear();
    ui_->propLabel->clear();

    currentPath_.clear();
    cleared_ = true;
}

void PreviewPanel::setItem(IconObject* item)
{
    if (!isVisible()) {
        if (!cleared_) {
            clear();
        }
        return;
    }

    if (item) {
        clear();
        currentPath_ = item->path().str();
        // can be an async call
        IconDescription::Instance()->getContents(item, this);
        // this data is generated on the fly
        ui_->propLabel->setText(IconDescription::Instance()->table(item, true));
    }
    else {
        // clear();
    }
}

void PreviewPanel::setContents(const std::string& path, QPixmap pix)
{
    if (currentPath_ == path) {
        ui_->contentsLabel->setPixmap(pix);
    }
}

void PreviewPanel::setContents(const std::string& path, QString txt)
{
    if (currentPath_ == path) {
        ui_->contentsLabel->setText(cssStyle_ + txt);
    }
}

void PreviewPanel::setContents(const std::string& path, QPixmap pix, QString txt)
{
    if (currentPath_ == path) {
        bool hasPix = !pix.isNull();
        bool hasTxt = !txt.isEmpty();

        if (hasPix && hasTxt) {
            ui_->contentsLabel->setTextAndPixmap(cssStyle_ + txt, pix);
        }
        else if (hasTxt) {
            ui_->contentsLabel->setText(cssStyle_ + txt);
        }
        else {
            ui_->contentsLabel->setPixmap(pix);
        }
    }
}

void PreviewPanel::paintEvent(QPaintEvent*)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
