/***************************** 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 "Metview.h"
#include "ResolveTransaction.h"
#include "TaskObserver.h"
#include "Action.h"
#include "IconObject.h"
#include "Request.h"
#include "Task.h"
#include "Folder.h"
#include "IconFactory.h"

#include "Protocol.h"

ResolveTransaction::ResolveTransaction() :
    Transaction("RESOLVE")
{
    std::cout << "Resolve::Resolve()" << std::endl;
}
ResolveTransaction::ResolveTransaction(MvTransaction* t) :
    Transaction(t)
{
    std::cout << "Resolve::Resolve()" << std::endl;
}

ResolveTransaction::~ResolveTransaction()
{
    std::cout << "Resolve::~Resolve()" << std::endl;
}

void ResolveTransaction::success(Task*, const Request& r)
{
    sendReply(r);
}

void ResolveTransaction::failure(Task*, const Request& r)
{
    setError(1, "Object failed");
    sendReply(MvRequest(r));
}

MvTransaction* ResolveTransaction::cloneSelf()
{
    return new ResolveTransaction(this);
}

void ResolveTransaction::callback(MvRequest& r)
{
    const char* name = r("NAME");
    IconObject* o = name ? IconObject::search(name) : nullptr;

    if (o == nullptr) {
        setError(1, "Cannot find object");
        sendReply(MvRequest());
        return;
    }

    Action a("prepare", "*");
    TaskH t = o->action(a);
    if (t)
        t->add(this);
    else
        sendReply(MvRequest());
}


static ProtocolFactory<ResolveTransaction> resolve;
