/***************************** LICENSE START ***********************************

 Copyright 2013 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 "MvQGeoHelp.h"

#include "HelpFactory.h"
#include "MvIconParameter.h"
#include "RequestPanel.h"

MvQGeoHelp::MvQGeoHelp(RequestPanel& owner, const MvIconParameter& param) :
    MvQRequestPanelHelp(owner, param)
{
}

void MvQGeoHelp::start()
{
    attach();  // Will be decremented by ReplyHandler, so make sure it stays alive.

    Request info = param_.interfaceRequest();

    Request request("EDIT_MAP");

    // The parameter is in lower case because it
    // will be used to build the icon filename
    Cached input          = info("input_type");
    request("INPUT_TYPE") = input.toUpper();

    request("INPUT_PARAM") = param_.name();

    request("CUSTOM_WIDTH")  = 14.8;
    request("CUSTOM_HEIGHT") = 10.5;


    request = request + owner_.request();

    observe();

    callService("GeoToolManager", request);
}

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

void MvQGeoHelp::set(Request& r)
{
    r.merge(request_);
    request_ = Request();
}

void MvQGeoHelp::reply(const Request& reply, int error)
{
    if (error == 0)
        reply.print();
}

void MvQGeoHelp::progress(const Request& progress)
{
    progress.print();
    request_ = progress;
    //owner_.changed(*this);
}

void MvQGeoHelp::message(const std::string& msg)
{
    std::cout << "MvQGeoHelp::message" << msg << std::endl;
}

void MvQGeoHelp::message(const Request& msg)
{
    std::string s = msg.getVerb();
    if (s != "INPUT")
        return;

    request_ = owner_.request();
    request_.merge(msg);

    int cnt = msg.countValues(param_.name());
    std::vector<std::string> res;
    for (int i = 0; i < cnt; ++i) {
        const char* ch;
        msg.getValue(ch, param_.name(), i);
        res.push_back(std::string(ch));
    }
    owner_.set(param_.name(), res);

    stop();  // stop observing the helper widget since it could be reused for other params

    //owner_.changed(*this);
}

QIcon MvQGeoHelp::dialogIcon()
{
    Request info = param_.interfaceRequest();

    if (const char* iconName = info("help_icon")) {
        return QIcon(QPixmap(":/desktop/" + QString(iconName) + ".svg"));
    }
    else if (const char* inpType = info("input_type")) {
        QString t(inpType);
        t = t.toLower();
        if (t == "area")
            t = "map";
        return QIcon(QPixmap(":/desktop/help_" + t + ".svg"));
    }
    return QIcon();
}


static HelpMaker<MvQGeoHelp> maker("help_input");
