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

#include <QLabel>
#include <QVBoxLayout>

#include "Folder.h"
#include "IconClass.h"
#include "IconInfo.h"
#include "IconFactory.h"
#include "HelpFactory.h"
#include "RequestPanel.h"

#include "MvQFolderModel.h"
#include "MvQIconHelpView.h"

MvQIconHelp::MvQIconHelp(RequestPanel& owner, const MvIconParameter& param) :
    MvQRequestPanelHelp(owner, param)
{
    multiple_ = param.multiple();

    //Create model
    model_ = new MvQFolderModel(parentWidget_);

    Folder* f = Folder::folder("templates",
                               owner.iconClass().defaultName(),
                               param.beautifiedName());

    model_->setFolder(f);
    model_->setAcceptedClasses(param.interfaceRequest().get("class"));

    //If the folder is empty try to create an icon from the help_definition
    fill(param);

    //Create view
    view_ = new MvQIconHelpView(model_, parentWidget_);
    //view_->setHelper(true);

    view_->setFixedHeight(80);
    view_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

    //Title
    QLabel* titleLabel = new QLabel(tr("Helper icons for: ") + QString::fromStdString(param.beautifiedName()), parentWidget_);

    //Layout
    QVBoxLayout* layout = new QVBoxLayout(parentWidget_);
    layout->setSpacing(3);
    layout->setContentsMargins(1, 1, 1, 1);

    holderW_ = new QWidget(parentWidget_);
    holderW_->setLayout(layout);
    layout->addWidget(titleLabel);
    layout->addWidget(view_);

    //QFont font;
    //QFontMetrics fm(font);
    //holderW_->setMinimumHeight(2*(fm.size(Qt::TextExpandTabs,"A").height()+32+10+5+10));
    //holderW_->setMaximumHeight(2*(fm.size(Qt::TextExpandTabs,"A").height()+32+10+5+10));

    //view_->toGrid();
}

QWidget* MvQIconHelp::widget()
{
    return holderW_;
}

void MvQIconHelp::refresh(const vector<string>& /*values*/)
{
}

void MvQIconHelp::fill(const MvIconParameter& param)
{
    Folder* f = model_->folder();

    if (!f)
        return;

    if (f->numOfIconKids() == 0) {
        Request i     = param.interfaceRequest();
        MvRequest p   = i("help_definition");
        const char* n = i("help_name");

        //Create a helper icon from the request
        if (p) {
            IconObject* o = IconFactory::create(model_->folder(), p, IconInfo::undefX(), IconInfo::undefY());
            if (n)
                o->rename(n);
        }
    }
}

static HelpMaker<MvQIconHelp> maker("help_data");
