/***************************** 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 "Metview.h"
#include "InternalTask.h"
#include "IconObject.h"
//#include "Log.h"
#include "Request.h"
#include "Dependancy.h"
#include "IconFactory.h"

//=================================================================

InternalTask::InternalTask(const Action& action, IconObject* o) :
    action_(action),
    object_(o),
    error_(false),
    waiting_(0)

{
}

InternalTask::~InternalTask()
{
    std::cout << "InternalTask::~InternalTask " << *object_ << std::endl;
}

void InternalTask::start()
{
    const std::set<DependancyH>& dep = object_->dependancies();

    Action action("prepare", "*");

    for (const auto& j : dep) {
        Task* t = j->action(action);
        if (t) {
            tasks_[t] = j;
            waiting_++;
            t->add(this);
        }
    }
    check();
}

void InternalTask::check()
{
    std::cout << *this << std::endl;

    if (waiting_)
        return;

    MvRequest r = object_->fullRequest();
    const char* null = nullptr;

    if (null == r("_NAME"))
        r("_NAME") = object_->fullName().c_str();
    if (null == r("_CLASS"))
        r("_CLASS") = object_->className().c_str();
    if (null == r("_ACTION"))
        r("_ACTION") = action_.name().c_str();

    if (error_)
        Task::failure(r);
    else
        Task::success(r);
}

void InternalTask::success(Task* t, const Request& r)
{
    std::cout << "InternalTask::success " << *t << std::endl;
    tasks_[t]->success(r);
    waiting_--;
    check();
}

void InternalTask::failure(Task* t, const Request& r)
{
    std::cout << "InternalTask::failure " << *t << std::endl;
    error_ = true;
    tasks_[t]->failure(r);
    waiting_--;
    check();
}

void InternalTask::print(std::ostream& s) const
{
    s << "InternalTask["
      << ","
      << action_.name()
      << ","
      << action_.mode()
      << ","
      << *object_
      << "]";
}
