/*****************************************************************************
*
* Copyright (c) 2000 - 2017, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

#include <PyTransferFunctionWidget.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <snprintf.h>

// ****************************************************************************
// Module: PyTransferFunctionWidget
//
// Purpose: 
//   Widget for 2D transfer function
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a TransferFunctionWidget.
//
struct TransferFunctionWidgetObject
{
    PyObject_HEAD
    TransferFunctionWidget *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewTransferFunctionWidget(int);

std::string
PyTransferFunctionWidget_ToString(const TransferFunctionWidget *atts, const char *prefix)
{
    std::string str;
    char tmpStr[1000];

    const char *Type_names = "Rectangle, Triangle, Paraboloid, Ellipsoid";
    switch (atts->GetType())
    {
      case TransferFunctionWidget::Rectangle:
          SNPRINTF(tmpStr, 1000, "%sType = %sRectangle  # %s\n", prefix, prefix, Type_names);
          str += tmpStr;
          break;
      case TransferFunctionWidget::Triangle:
          SNPRINTF(tmpStr, 1000, "%sType = %sTriangle  # %s\n", prefix, prefix, Type_names);
          str += tmpStr;
          break;
      case TransferFunctionWidget::Paraboloid:
          SNPRINTF(tmpStr, 1000, "%sType = %sParaboloid  # %s\n", prefix, prefix, Type_names);
          str += tmpStr;
          break;
      case TransferFunctionWidget::Ellipsoid:
          SNPRINTF(tmpStr, 1000, "%sType = %sEllipsoid  # %s\n", prefix, prefix, Type_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    SNPRINTF(tmpStr, 1000, "%sName = \"%s\"\n", prefix, atts->GetName().c_str());
    str += tmpStr;
    {   const float *BaseColor = atts->GetBaseColor();
        SNPRINTF(tmpStr, 1000, "%sBaseColor = (", prefix);
        str += tmpStr;
        for(int i = 0; i < 4; ++i)
        {
            SNPRINTF(tmpStr, 1000, "%g", BaseColor[i]);
            str += tmpStr;
            if(i < 3)
            {
                SNPRINTF(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        SNPRINTF(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    {   const float *Position = atts->GetPosition();
        SNPRINTF(tmpStr, 1000, "%sPosition = (", prefix);
        str += tmpStr;
        for(int i = 0; i < 8; ++i)
        {
            SNPRINTF(tmpStr, 1000, "%g", Position[i]);
            str += tmpStr;
            if(i < 7)
            {
                SNPRINTF(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        SNPRINTF(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    return str;
}

static PyObject *
TransferFunctionWidget_Notify(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
TransferFunctionWidget_SetType(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;

    int ival;
    if(!PyArg_ParseTuple(args, "i", &ival))
        return NULL;

    // Set the Type in the object.
    if(ival >= 0 && ival < 4)
        obj->data->SetType(TransferFunctionWidget::WidgetType(ival));
    else
    {
        fprintf(stderr, "An invalid Type value was given. "
                        "Valid values are in the range of [0,3]. "
                        "You can also use the following names: "
                        "Rectangle, Triangle, Paraboloid, Ellipsoid.");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
TransferFunctionWidget_GetType(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;
    PyObject *retval = PyInt_FromLong(long(obj->data->GetType()));
    return retval;
}

/*static*/ PyObject *
TransferFunctionWidget_SetName(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;

    char *str;
    if(!PyArg_ParseTuple(args, "s", &str))
        return NULL;

    // Set the Name in the object.
    obj->data->SetName(std::string(str));

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
TransferFunctionWidget_GetName(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;
    PyObject *retval = PyString_FromString(obj->data->GetName().c_str());
    return retval;
}

/*static*/ PyObject *
TransferFunctionWidget_SetBaseColor(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;

    float *fvals = obj->data->GetBaseColor();
    if(!PyArg_ParseTuple(args, "ffff", &fvals[0], &fvals[1], &fvals[2], &fvals[3]))
    {
        PyObject     *tuple;
        if(!PyArg_ParseTuple(args, "O", &tuple))
            return NULL;

        if(PyTuple_Check(tuple))
        {
            if(PyTuple_Size(tuple) != 4)
                return NULL;

            PyErr_Clear();
            for(int i = 0; i < PyTuple_Size(tuple); ++i)
            {
                PyObject *item = PyTuple_GET_ITEM(tuple, i);
                if(PyFloat_Check(item))
                    fvals[i] = float(PyFloat_AS_DOUBLE(item));
                else if(PyInt_Check(item))
                    fvals[i] = float(PyInt_AS_LONG(item));
                else if(PyLong_Check(item))
                    fvals[i] = float(PyLong_AsDouble(item));
                else
                    fvals[i] = 0.;
            }
        }
        else
            return NULL;
    }

    // Mark the BaseColor in the object as modified.
    obj->data->SelectBaseColor();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
TransferFunctionWidget_GetBaseColor(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;
    // Allocate a tuple the with enough entries to hold the BaseColor.
    PyObject *retval = PyTuple_New(4);
    const float *BaseColor = obj->data->GetBaseColor();
    for(int i = 0; i < 4; ++i)
        PyTuple_SET_ITEM(retval, i, PyFloat_FromDouble(double(BaseColor[i])));
    return retval;
}

/*static*/ PyObject *
TransferFunctionWidget_SetPosition(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;

    float *fvals = obj->data->GetPosition();
    if(!PyArg_ParseTuple(args, "ffffffff", &fvals[0], &fvals[1], &fvals[2], &fvals[3], &fvals[4], &fvals[5], &fvals[6], &fvals[7]))
    {
        PyObject     *tuple;
        if(!PyArg_ParseTuple(args, "O", &tuple))
            return NULL;

        if(PyTuple_Check(tuple))
        {
            if(PyTuple_Size(tuple) != 8)
                return NULL;

            PyErr_Clear();
            for(int i = 0; i < PyTuple_Size(tuple); ++i)
            {
                PyObject *item = PyTuple_GET_ITEM(tuple, i);
                if(PyFloat_Check(item))
                    fvals[i] = float(PyFloat_AS_DOUBLE(item));
                else if(PyInt_Check(item))
                    fvals[i] = float(PyInt_AS_LONG(item));
                else if(PyLong_Check(item))
                    fvals[i] = float(PyLong_AsDouble(item));
                else
                    fvals[i] = 0.;
            }
        }
        else
            return NULL;
    }

    // Mark the Position in the object as modified.
    obj->data->SelectPosition();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
TransferFunctionWidget_GetPosition(PyObject *self, PyObject *args)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)self;
    // Allocate a tuple the with enough entries to hold the Position.
    PyObject *retval = PyTuple_New(8);
    const float *Position = obj->data->GetPosition();
    for(int i = 0; i < 8; ++i)
        PyTuple_SET_ITEM(retval, i, PyFloat_FromDouble(double(Position[i])));
    return retval;
}



PyMethodDef PyTransferFunctionWidget_methods[TRANSFERFUNCTIONWIDGET_NMETH] = {
    {"Notify", TransferFunctionWidget_Notify, METH_VARARGS},
    {"SetType", TransferFunctionWidget_SetType, METH_VARARGS},
    {"GetType", TransferFunctionWidget_GetType, METH_VARARGS},
    {"SetName", TransferFunctionWidget_SetName, METH_VARARGS},
    {"GetName", TransferFunctionWidget_GetName, METH_VARARGS},
    {"SetBaseColor", TransferFunctionWidget_SetBaseColor, METH_VARARGS},
    {"GetBaseColor", TransferFunctionWidget_GetBaseColor, METH_VARARGS},
    {"SetPosition", TransferFunctionWidget_SetPosition, METH_VARARGS},
    {"GetPosition", TransferFunctionWidget_GetPosition, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
TransferFunctionWidget_dealloc(PyObject *v)
{
   TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static int
TransferFunctionWidget_compare(PyObject *v, PyObject *w)
{
    TransferFunctionWidget *a = ((TransferFunctionWidgetObject *)v)->data;
    TransferFunctionWidget *b = ((TransferFunctionWidgetObject *)w)->data;
    return (*a == *b) ? 0 : -1;
}

PyObject *
PyTransferFunctionWidget_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "Type") == 0)
        return TransferFunctionWidget_GetType(self, NULL);
    if(strcmp(name, "Rectangle") == 0)
        return PyInt_FromLong(long(TransferFunctionWidget::Rectangle));
    if(strcmp(name, "Triangle") == 0)
        return PyInt_FromLong(long(TransferFunctionWidget::Triangle));
    if(strcmp(name, "Paraboloid") == 0)
        return PyInt_FromLong(long(TransferFunctionWidget::Paraboloid));
    if(strcmp(name, "Ellipsoid") == 0)
        return PyInt_FromLong(long(TransferFunctionWidget::Ellipsoid));

    if(strcmp(name, "Name") == 0)
        return TransferFunctionWidget_GetName(self, NULL);
    if(strcmp(name, "BaseColor") == 0)
        return TransferFunctionWidget_GetBaseColor(self, NULL);
    if(strcmp(name, "Position") == 0)
        return TransferFunctionWidget_GetPosition(self, NULL);

    return Py_FindMethod(PyTransferFunctionWidget_methods, self, name);
}

int
PyTransferFunctionWidget_setattr(PyObject *self, char *name, PyObject *args)
{
    // Create a tuple to contain the arguments since all of the Set
    // functions expect a tuple.
    PyObject *tuple = PyTuple_New(1);
    PyTuple_SET_ITEM(tuple, 0, args);
    Py_INCREF(args);
    PyObject *obj = NULL;

    if(strcmp(name, "Type") == 0)
        obj = TransferFunctionWidget_SetType(self, tuple);
    else if(strcmp(name, "Name") == 0)
        obj = TransferFunctionWidget_SetName(self, tuple);
    else if(strcmp(name, "BaseColor") == 0)
        obj = TransferFunctionWidget_SetBaseColor(self, tuple);
    else if(strcmp(name, "Position") == 0)
        obj = TransferFunctionWidget_SetPosition(self, tuple);

    if(obj != NULL)
        Py_DECREF(obj);

    Py_DECREF(tuple);
    if( obj == NULL)
        PyErr_Format(PyExc_RuntimeError, "Unable to set unknown attribute: '%s'", name);
    return (obj != NULL) ? 0 : -1;
}

static int
TransferFunctionWidget_print(PyObject *v, FILE *fp, int flags)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)v;
    fprintf(fp, "%s", PyTransferFunctionWidget_ToString(obj->data, "").c_str());
    return 0;
}

PyObject *
TransferFunctionWidget_str(PyObject *v)
{
    TransferFunctionWidgetObject *obj = (TransferFunctionWidgetObject *)v;
    return PyString_FromString(PyTransferFunctionWidget_ToString(obj->data,"").c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *TransferFunctionWidget_Purpose = "Widget for 2D transfer function";
#else
static char *TransferFunctionWidget_Purpose = "Widget for 2D transfer function";
#endif

//
// The type description structure
//
static PyTypeObject TransferFunctionWidgetType =
{
    //
    // Type header
    //
    PyObject_HEAD_INIT(&PyType_Type)
    0,                                   // ob_size
    "TransferFunctionWidget",                    // tp_name
    sizeof(TransferFunctionWidgetObject),        // tp_basicsize
    0,                                   // tp_itemsize
    //
    // Standard methods
    //
    (destructor)TransferFunctionWidget_dealloc,  // tp_dealloc
    (printfunc)TransferFunctionWidget_print,     // tp_print
    (getattrfunc)PyTransferFunctionWidget_getattr, // tp_getattr
    (setattrfunc)PyTransferFunctionWidget_setattr, // tp_setattr
    (cmpfunc)TransferFunctionWidget_compare,     // tp_compare
    (reprfunc)0,                         // tp_repr
    //
    // Type categories
    //
    0,                                   // tp_as_number
    0,                                   // tp_as_sequence
    0,                                   // tp_as_mapping
    //
    // More methods
    //
    0,                                   // tp_hash
    0,                                   // tp_call
    (reprfunc)TransferFunctionWidget_str,        // tp_str
    0,                                   // tp_getattro
    0,                                   // tp_setattro
    0,                                   // tp_as_buffer
    Py_TPFLAGS_CHECKTYPES,               // tp_flags
    TransferFunctionWidget_Purpose,              // tp_doc
    0,                                   // tp_traverse
    0,                                   // tp_clear
    0,                                   // tp_richcompare
    0                                    // tp_weaklistoffset
};

//
// Helper functions for object allocation.
//

static TransferFunctionWidget *defaultAtts = 0;
static TransferFunctionWidget *currentAtts = 0;

static PyObject *
NewTransferFunctionWidget(int useCurrent)
{
    TransferFunctionWidgetObject *newObject;
    newObject = PyObject_NEW(TransferFunctionWidgetObject, &TransferFunctionWidgetType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new TransferFunctionWidget(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new TransferFunctionWidget(*defaultAtts);
    else
        newObject->data = new TransferFunctionWidget;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapTransferFunctionWidget(const TransferFunctionWidget *attr)
{
    TransferFunctionWidgetObject *newObject;
    newObject = PyObject_NEW(TransferFunctionWidgetObject, &TransferFunctionWidgetType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (TransferFunctionWidget *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
TransferFunctionWidget_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewTransferFunctionWidget(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef TransferFunctionWidgetMethods[] = {
    {"TransferFunctionWidget", TransferFunctionWidget_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *TransferFunctionWidgetObserver = 0;

std::string
PyTransferFunctionWidget_GetLogString()
{
    std::string s("TransferFunctionWidget = TransferFunctionWidget()\n");
    if(currentAtts != 0)
        s += PyTransferFunctionWidget_ToString(currentAtts, "TransferFunctionWidget.");
    return s;
}

static void
PyTransferFunctionWidget_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("TransferFunctionWidget = TransferFunctionWidget()\n");
        s += PyTransferFunctionWidget_ToString(currentAtts, "TransferFunctionWidget.");
        cb(s);
    }
}

void
PyTransferFunctionWidget_StartUp(TransferFunctionWidget *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyTransferFunctionWidget_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(TransferFunctionWidgetObserver == 0)
    {
        TransferFunctionWidgetObserver = new ObserverToCallback(subj,
            PyTransferFunctionWidget_CallLogRoutine, (void *)data);
    }

}

void
PyTransferFunctionWidget_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete TransferFunctionWidgetObserver;
    TransferFunctionWidgetObserver = 0;
}

PyMethodDef *
PyTransferFunctionWidget_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return TransferFunctionWidgetMethods;
}

bool
PyTransferFunctionWidget_Check(PyObject *obj)
{
    return (obj->ob_type == &TransferFunctionWidgetType);
}

TransferFunctionWidget *
PyTransferFunctionWidget_FromPyObject(PyObject *obj)
{
    TransferFunctionWidgetObject *obj2 = (TransferFunctionWidgetObject *)obj;
    return obj2->data;
}

PyObject *
PyTransferFunctionWidget_New()
{
    return NewTransferFunctionWidget(0);
}

PyObject *
PyTransferFunctionWidget_Wrap(const TransferFunctionWidget *attr)
{
    return WrapTransferFunctionWidget(attr);
}

void
PyTransferFunctionWidget_SetParent(PyObject *obj, PyObject *parent)
{
    TransferFunctionWidgetObject *obj2 = (TransferFunctionWidgetObject *)obj;
    obj2->parent = parent;
}

void
PyTransferFunctionWidget_SetDefaults(const TransferFunctionWidget *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new TransferFunctionWidget(*atts);
}

