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

#include "Action.h"
#include "Task.h"
#include "IconClass.h"

Drop::Drop(const std::set<IconObject*>& icons,
           const Request& request,
           const std::string& service, const Request& mode,
           QObject* parent) :
    QObject(parent),
    request_(request),
    service_(service),
    mode_(mode),
    error_(false),
    waiting_(0)
{
    for (auto icon : icons) {
        IconObjectH o = icon;
        requests_[o] = o->request();
        Task* t = o->action(Action("prepare", "*"));

        if (t) {
            tasks_[t] = o;
            waiting_++;
            t->add(this);

            // Add extra information about the target object
            MvRequest reqCont = request.getSubrequest("_CONTEXT");
            if (reqCont)
                t->addContext(reqCont);
        }
    }
    check();
}

Drop::~Drop() = default;

void Drop::success(Task* t, const Request& r)
{
    IconObjectH o = tasks_[t];
    requests_[o] = r;
    waiting_--;
    check();
}

void Drop::failure(Task* t, const Request& r)
{
    IconObjectH o = tasks_[t];
    requests_[o] = r;

    error_ = true;
    waiting_--;
    check();
}

void Drop::check()
{
    if (waiting_)
        return;

    if (!error_) {
        // Request should be sorted
        const char* null = nullptr;
        std::map<int, std::vector<Request> > m;

        for (auto& request : requests_) {
            Request r = request.second;
            IconObject* o = request.first;
            if (r && r.getVerb()) {
                int priority = IconClass::find(r.getVerb()).priority();
                if (null == r("_NAME"))
                    r("_NAME") = o->fullName().c_str();
                if (null == r("_CLASS"))
                    r("_CLASS") = o->className().c_str();
                m[priority].push_back(r);
            }
        }

        Request req;

        for (auto& k : m) {
            Request r;
            for (auto& j : k.second)
                r = r + j + req;
            req = r;
        }

        request_ = request_ + req;
        request_("_MODE") = mode_;

        MvApplication::callService(service_.c_str(), request_, nullptr);
    }
    else {
        auto it = requests_.begin();
        request_ = (*it).second;

        MvApplication::callService(service_.c_str(), request_, nullptr);
    }

    this->deleteLater();
}
