/***************************** 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 *************************************/

#pragma once

#include <Metview.h>


//! (not used; obsolete?)
template <class T>
class TMvTransaction : public MvTransaction
{
    TMvTransaction(MvTransaction* t) :
        MvTransaction(t) {}
    MvTransaction* cloneSelf() { return new TMvTransaction<T>(this); }

public:
    TMvTransaction() :
        MvTransaction(T::name()) {}

    void callback(MvRequest&);
};

//==========================================================================
// An other way is the following


// TODO: this should be a generic class and
//       uplot specific code should not be here!!!

template <class T>
class TMvServe : public MvTransaction
{
private:
    T& object_;
    std::string outParamName_;
    bool exitOnError_{true};

public:
    TMvServe(T& object, const char* name, const std::string& outParamName, bool exitOnError) :
        MvTransaction(name),
        object_(object),
        outParamName_(outParamName),
        exitOnError_(exitOnError) {}

    TMvServe(TMvServe<T>* other) :
        MvTransaction(other),
        object_(other->object_),
        outParamName_(other->outParamName_),
        exitOnError_(other->exitOnError_) {}

    MvTransaction* cloneSelf() { return new TMvServe(this); }

    void callback(MvRequest& in)
    {
        object_.serve(*this, in);

        // Specially important for Macro&MetviewUI
        // Macro ("execute" & "not_screen") calls uPlotBatch
        // which needs to inform back that it has finished
        // sucessfully or not
        MvRequest out;
        if (getError()) {
            out.setVerb("ERROR");

            // Get icon name(s) involved on the operation
            if ((const char*)in("ICON_NAME")) {
                int cnt = in.iterInit("ICON_NAME");
                for (int i = 0; i < cnt; i++) {
                    const char* iconChName;
                    in.iterGetNextValue(iconChName);
                    if (iconChName) {
                        if (i == 0)
                            out.setValue("ICON_NAME", iconChName);
                        else
                            out.addValue("ICON_NAME", iconChName);
                    }
                }
            }
            else if ((const char*)in("PATH")) {
                const char* iconChName = mbasename((const char*)in("PATH"));
                out.setValue("ICON_NAME", iconChName);
            }

            // Get error message(s)
            const char* msg;
            int n = 0;
            while ((msg = getMessage(n++))) {
                if (n == 1)
                    out.setValue("MESSAGE", msg);
                else
                    out.addValue("MESSAGE", msg);
            }

            out.print();

            saveOutRequest(in, out);

            // Send reply to sender
            sendReply(out);

            // In this version, we are killing uPlot.
            // In order to keep uPlot alive, we need to remove from
            // the database (maybe other structures too) all the requests
            // that caused the error
            // Root::Instance().Clean();
            if (exitOnError_) {
                exit(0);
            }
        }
        else {
            saveOutRequest(in, out);
            sendReply(out);
        }
    }

    void saveOutRequest(const MvRequest& in, const MvRequest& out)
    {
        // Save request to be processed by uPlotManager?
        if (!outParamName_.empty()) {
            // if ((const char*)in("_UPLOT_MANAGER_ID"))
            if (const char* ch = in(outParamName_.c_str())) {
                out.save(ch);
            }
        }
    }
};

template <class T>
void registerTMvServe(T& object, const char* name, const std::string& outParamName, bool exitOnError)
{
    new TMvServe<T>(object, name, outParamName, exitOnError);
}

//==========================================================================
//
// Template to create an asynchronous functions
//
// use as above:

#ifndef DOXYGEN_SHOULD_SKIP_THIS

// it seems that this template is not used anywhere (2008-04-10/vk)

template <class T>
class TMvFunction : public MvFunction
{
protected:
    char* Info;
    TMvFunction(MvTransaction* t) :
        MvFunction(t) {}
    MvTransaction* cloneSelf() { return new TMvFunction<T>(this); }
    char* getInfo() { return Info; }

public:
    TMvFunction() :
        MvFunction(T::name(), T::args())
    {
        Info = T::info();
    }
    void callback(MvRequest&);
};
#endif
