/***************************** 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 "IconGroupTools.h"
#include "ConfigLoader.h"
#include "Request.h"
#include "Log.h"
#include "MvLog.h"
#include "MvQMessageBox.h"
#include "ReplyErrorParser.h"

#include <string>
#include <vector>

static std::vector<IconGroupTools*> tools;


//=================================================================
//
// IconGroupTask
//
//=================================================================

IconGroupTask::IconGroupTask(const std::string& service, const MvRequest& r) :
    service_(service),
    request_(r)
{
}

void IconGroupTask::start()
{
    MvLog().dbg() << MV_FN_INFO <<  " ---> send " << *this;
    request_.print();

    callService(service_, request_);

    MvLog().dbg() << " <--- send " << *this;
}

void IconGroupTask::reply(const Request& r, int err)
{
    MvLog().dbg() << MV_FN_INFO <<  "err=" << err;
    if (err)
        Task::failure(r);
    else
        Task::success(r);
}

IconGroupTools::IconGroupTools(request* r) :
    request_(r)
{
}

//=================================================================
//
// IconGroupTask
//
//=================================================================

IconGroupTools::~IconGroupTools() = default;

std::string IconGroupTools::name()
{
    return {get_value(request_, "name", 0)};
}

bool IconGroupTools::popupOnError() const
{
    auto v = get_value(request_, "popup_on_error", 0);
    return (v == nullptr)?true:(strcmp(v, "true") == 0);
}

bool IconGroupTools::can(const std::string& name)
{
    for (auto& tool : tools)
        if (tool->name() == name)
            return true;
    return false;
}

void IconGroupTools::run(const std::string& name, const std::vector<IconObject*>& items)
{
    for (auto& tool : tools)
        if (tool->name() == name)
            tool->run(items);
}

void IconGroupTools::run(const std::vector<IconObject*>& items)
{
    MvRequest r(get_value(request_, "action", 0));

    if (const char* par = get_value(request_, "param", 0)) {
        r.setValue("PARAM", par);
    }

    for (auto item : items) {
        r.addValue("ITEMS", item->fullName().c_str());
    }

    // indicate that the ui manager should wait for the ui app to finish!!
    r("_WAIT_APP") = "1";

    std::string serviceName = get_value(request_, "service", 0);

    // task will automatciallt deleted when the reply arrives
    Task* t = new IconGroupTask(serviceName, r);
    t->add(this);
    t->start();
}


void IconGroupTools::load(request* r)
{
    tools.push_back(new IconGroupTools(r));
}

void IconGroupTools::success(Task*, const Request&)
{
}

void IconGroupTools::failure(Task*, const Request& r)
{
//    std::cout << " ---> reply " << *this << std::endl;
    r.print();
//    std::cout << "action = " << action_.name() << std::endl;
//    std::cout << " <--- reply " << *this << std::endl;

    ReplyErrorParser p(r);
    for (std::size_t i=0; i < p.items().size(); i++) {
        auto o = p.items()[i];
        if (o != nullptr) {
            o->notifyError();
            if (p.items().size() == p.itemsError().size()) {
                Log::error(o) << p.itemsError()[i] << std::endl;
            } else if (!p.error().empty()) {
                Log::error(o) << p.error() << std::endl;
            }
        }
    }

    if (popupOnError()) {
        MvQMessageBox mb(p);
    }

}

static SimpleLoader<IconGroupTools> loadClasses("desktop_icon_group_tool", 1);
