/*****************************************************************************
*
* Copyright (c) 2000 - 2018, 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 <PyColorTableAttributes.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <snprintf.h>
#include <PyColorControlPointList.h>

// ****************************************************************************
// Module: PyColorTableAttributes
//
// Purpose: 
//   This class contains the list of colortables.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

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

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

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

    {   const stringVector &names = atts->GetNames();
        SNPRINTF(tmpStr, 1000, "%snames = (", prefix);
        str += tmpStr;
        for(size_t i = 0; i < names.size(); ++i)
        {
            SNPRINTF(tmpStr, 1000, "\"%s\"", names[i].c_str());
            str += tmpStr;
            if(i < names.size() - 1)
            {
                SNPRINTF(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        SNPRINTF(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    { // new scope
        int index = 0;
        // Create string representation of colorTables from atts.
        for(AttributeGroupVector::const_iterator pos = atts->GetColorTables().begin(); pos != atts->GetColorTables().end(); ++pos, ++index)
        {
            const ColorControlPointList *current = (const ColorControlPointList *)(*pos);
            SNPRINTF(tmpStr, 1000, "GetColorTables(%d).", index);
            std::string objPrefix(prefix + std::string(tmpStr));
            str += PyColorControlPointList_ToString(current, objPrefix.c_str());
        }
        if(index == 0)
            str += "#colorTables does not contain any ColorControlPointList objects.\n";
    }
    SNPRINTF(tmpStr, 1000, "%sactiveContinuous = \"%s\"\n", prefix, atts->GetActiveContinuous().c_str());
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%sactiveDiscrete = \"%s\"\n", prefix, atts->GetActiveDiscrete().c_str());
    str += tmpStr;
    if(atts->GetGroupingFlag())
        SNPRINTF(tmpStr, 1000, "%sgroupingFlag = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%sgroupingFlag = 0\n", prefix);
    str += tmpStr;
    return str;
}

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

/*static*/ PyObject *
ColorTableAttributes_SetNames(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;

    stringVector  &vec = obj->data->GetNames();
    PyObject     *tuple;
    if(!PyArg_ParseTuple(args, "O", &tuple))
        return NULL;

    if(PyTuple_Check(tuple))
    {
        vec.resize(PyTuple_Size(tuple));
        for(int i = 0; i < PyTuple_Size(tuple); ++i)
        {
            PyObject *item = PyTuple_GET_ITEM(tuple, i);
            if(PyString_Check(item))
                vec[i] = std::string(PyString_AS_STRING(item));
            else
                vec[i] = std::string("");
        }
    }
    else if(PyString_Check(tuple))
    {
        vec.resize(1);
        vec[0] = std::string(PyString_AS_STRING(tuple));
    }
    else
        return NULL;

    // Mark the names in the object as modified.
    obj->data->SelectNames();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorTableAttributes_GetNames(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    // Allocate a tuple the with enough entries to hold the names.
    const stringVector &names = obj->data->GetNames();
    PyObject *retval = PyTuple_New(names.size());
    for(size_t i = 0; i < names.size(); ++i)
        PyTuple_SET_ITEM(retval, i, PyString_FromString(names[i].c_str()));
    return retval;
}

/*static*/ PyObject *
ColorTableAttributes_GetColorTables(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    int index;
    if(!PyArg_ParseTuple(args, "i", &index))
        return NULL;
    if(index < 0 || (size_t)index >= obj->data->GetColorTables().size())
    {
        char msg[400] = {'\0'};
        if(obj->data->GetColorTables().size() == 0)
            SNPRINTF(msg, 400, "In ColorTableAttributes::GetColorTables : The index %d is invalid because colorTables is empty.", index);
        else
            SNPRINTF(msg, 400, "In ColorTableAttributes::GetColorTables : The index %d is invalid. Use index values in: [0, %ld).",  index, obj->data->GetColorTables().size());
        PyErr_SetString(PyExc_IndexError, msg);
        return NULL;
    }

    // Since the new object will point to data owned by the this object,
    // we need to increment the reference count.
    Py_INCREF(self);

    PyObject *retval = PyColorControlPointList_Wrap(&obj->data->GetColorTables(index));
    // Set the object's parent so the reference to the parent can be decref'd
    // when the child goes out of scope.
    PyColorControlPointList_SetParent(retval, self);

    return retval;
}

PyObject *
ColorTableAttributes_GetNumColorTables(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    return PyInt_FromLong((long)obj->data->GetColorTables().size());
}

PyObject *
ColorTableAttributes_AddColorTables(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PyColorControlPointList_Check(element))
    {
        char msg[400] = {'\0'};
        SNPRINTF(msg, 400, "The ColorTableAttributes::AddColorTables method only accepts ColorControlPointList objects.");
        PyErr_SetString(PyExc_TypeError, msg);
        return NULL;
    }
    ColorControlPointList *newData = PyColorControlPointList_FromPyObject(element);
    obj->data->AddColorTables(*newData);
    obj->data->SelectColorTables();
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
ColorTableAttributes_Remove_One_ColorTables(PyObject *self, int index)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    // Remove in the AttributeGroupVector instead of calling RemoveColorTables() because we don't want to delete the object; just remove it.
    AttributeGroupVector &atts = obj->data->GetColorTables();
    AttributeGroupVector::iterator pos = atts.begin();
    // Iterate through the vector "index" times. 
    for(int i = 0; i < index; ++i)
        ++pos;

    // If pos is still a valid iterator, remove that element.
    if(pos != atts.end())
    {
        // NOTE: Leak the object since other Python objects may reference it. Ideally,
        // we would put the object into some type of pool to be cleaned up later but
        // this will do for now.
        //
        // delete *pos;
        atts.erase(pos);
    }

    obj->data->SelectColorTables();
    Py_INCREF(Py_None);
    return Py_None;
}

PyObject *
ColorTableAttributes_RemoveColorTables(PyObject *self, PyObject *args)
{
    int index;
    if(!PyArg_ParseTuple(args, "i", &index))
        return NULL;
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    if(index < 0 || index >= obj->data->GetNumColorTables())
    {
        char msg[400] = {'\0'};
        SNPRINTF(msg, 400, "In ColorTableAttributes::RemoveColorTables : Index %d is out of range", index);
        PyErr_SetString(PyExc_IndexError, msg);
        return NULL;
    }

    return ColorTableAttributes_Remove_One_ColorTables(self, index);
}

PyObject *
ColorTableAttributes_ClearColorTables(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    int n = obj->data->GetNumColorTables();
    for(int i = 0; i < n; ++i)
    {
        ColorTableAttributes_Remove_One_ColorTables(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorTableAttributes_SetActiveContinuous(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;

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

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

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorTableAttributes_GetActiveContinuous(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    PyObject *retval = PyString_FromString(obj->data->GetActiveContinuous().c_str());
    return retval;
}

/*static*/ PyObject *
ColorTableAttributes_SetActiveDiscrete(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;

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

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

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorTableAttributes_GetActiveDiscrete(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    PyObject *retval = PyString_FromString(obj->data->GetActiveDiscrete().c_str());
    return retval;
}

/*static*/ PyObject *
ColorTableAttributes_SetGroupingFlag(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;

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

    // Set the groupingFlag in the object.
    obj->data->SetGroupingFlag(ival != 0);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorTableAttributes_GetGroupingFlag(PyObject *self, PyObject *args)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)self;
    PyObject *retval = PyInt_FromLong(obj->data->GetGroupingFlag()?1L:0L);
    return retval;
}



PyMethodDef PyColorTableAttributes_methods[COLORTABLEATTRIBUTES_NMETH] = {
    {"Notify", ColorTableAttributes_Notify, METH_VARARGS},
    {"SetNames", ColorTableAttributes_SetNames, METH_VARARGS},
    {"GetNames", ColorTableAttributes_GetNames, METH_VARARGS},
    {"GetColorTables", ColorTableAttributes_GetColorTables, METH_VARARGS},
    {"GetNumColorTables", ColorTableAttributes_GetNumColorTables, METH_VARARGS},
    {"AddColorTables", ColorTableAttributes_AddColorTables, METH_VARARGS},
    {"RemoveColorTables", ColorTableAttributes_RemoveColorTables, METH_VARARGS},
    {"ClearColorTables", ColorTableAttributes_ClearColorTables, METH_VARARGS},
    {"SetActiveContinuous", ColorTableAttributes_SetActiveContinuous, METH_VARARGS},
    {"GetActiveContinuous", ColorTableAttributes_GetActiveContinuous, METH_VARARGS},
    {"SetActiveDiscrete", ColorTableAttributes_SetActiveDiscrete, METH_VARARGS},
    {"GetActiveDiscrete", ColorTableAttributes_GetActiveDiscrete, METH_VARARGS},
    {"SetGroupingFlag", ColorTableAttributes_SetGroupingFlag, METH_VARARGS},
    {"GetGroupingFlag", ColorTableAttributes_GetGroupingFlag, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

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

static int
ColorTableAttributes_compare(PyObject *v, PyObject *w)
{
    ColorTableAttributes *a = ((ColorTableAttributesObject *)v)->data;
    ColorTableAttributes *b = ((ColorTableAttributesObject *)w)->data;
    return (*a == *b) ? 0 : -1;
}

PyObject *
PyColorTableAttributes_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "names") == 0)
        return ColorTableAttributes_GetNames(self, NULL);
    if(strcmp(name, "colorTables") == 0)
        return ColorTableAttributes_GetColorTables(self, NULL);
    if(strcmp(name, "activeContinuous") == 0)
        return ColorTableAttributes_GetActiveContinuous(self, NULL);
    if(strcmp(name, "activeDiscrete") == 0)
        return ColorTableAttributes_GetActiveDiscrete(self, NULL);
    if(strcmp(name, "groupingFlag") == 0)
        return ColorTableAttributes_GetGroupingFlag(self, NULL);

    return Py_FindMethod(PyColorTableAttributes_methods, self, name);
}

int
PyColorTableAttributes_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, "names") == 0)
        obj = ColorTableAttributes_SetNames(self, tuple);
    else if(strcmp(name, "activeContinuous") == 0)
        obj = ColorTableAttributes_SetActiveContinuous(self, tuple);
    else if(strcmp(name, "activeDiscrete") == 0)
        obj = ColorTableAttributes_SetActiveDiscrete(self, tuple);
    else if(strcmp(name, "groupingFlag") == 0)
        obj = ColorTableAttributes_SetGroupingFlag(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
ColorTableAttributes_print(PyObject *v, FILE *fp, int flags)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)v;
    fprintf(fp, "%s", PyColorTableAttributes_ToString(obj->data, "").c_str());
    return 0;
}

PyObject *
ColorTableAttributes_str(PyObject *v)
{
    ColorTableAttributesObject *obj = (ColorTableAttributesObject *)v;
    return PyString_FromString(PyColorTableAttributes_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 *ColorTableAttributes_Purpose = "This class contains the list of colortables.";
#else
static char *ColorTableAttributes_Purpose = "This class contains the list of colortables.";
#endif

//
// The type description structure
//
static PyTypeObject ColorTableAttributesType =
{
    //
    // Type header
    //
    PyObject_HEAD_INIT(&PyType_Type)
    0,                                   // ob_size
    "ColorTableAttributes",                    // tp_name
    sizeof(ColorTableAttributesObject),        // tp_basicsize
    0,                                   // tp_itemsize
    //
    // Standard methods
    //
    (destructor)ColorTableAttributes_dealloc,  // tp_dealloc
    (printfunc)ColorTableAttributes_print,     // tp_print
    (getattrfunc)PyColorTableAttributes_getattr, // tp_getattr
    (setattrfunc)PyColorTableAttributes_setattr, // tp_setattr
    (cmpfunc)ColorTableAttributes_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)ColorTableAttributes_str,        // tp_str
    0,                                   // tp_getattro
    0,                                   // tp_setattro
    0,                                   // tp_as_buffer
    Py_TPFLAGS_CHECKTYPES,               // tp_flags
    ColorTableAttributes_Purpose,              // tp_doc
    0,                                   // tp_traverse
    0,                                   // tp_clear
    0,                                   // tp_richcompare
    0                                    // tp_weaklistoffset
};

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

static ColorTableAttributes *defaultAtts = 0;
static ColorTableAttributes *currentAtts = 0;

static PyObject *
NewColorTableAttributes(int useCurrent)
{
    ColorTableAttributesObject *newObject;
    newObject = PyObject_NEW(ColorTableAttributesObject, &ColorTableAttributesType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new ColorTableAttributes(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new ColorTableAttributes(*defaultAtts);
    else
        newObject->data = new ColorTableAttributes;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapColorTableAttributes(const ColorTableAttributes *attr)
{
    ColorTableAttributesObject *newObject;
    newObject = PyObject_NEW(ColorTableAttributesObject, &ColorTableAttributesType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (ColorTableAttributes *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

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

PyObject *
ColorTableAttributes_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 *)NewColorTableAttributes(useCurrent);
}

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

static Observer *ColorTableAttributesObserver = 0;

std::string
PyColorTableAttributes_GetLogString()
{
    std::string s("ColorTableAtts = ColorTableAttributes()\n");
    if(currentAtts != 0)
        s += PyColorTableAttributes_ToString(currentAtts, "ColorTableAtts.");
    return s;
}

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

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

void
PyColorTableAttributes_StartUp(ColorTableAttributes *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyColorTableAttributes_SetDefaults(subj);

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

}

void
PyColorTableAttributes_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete ColorTableAttributesObserver;
    ColorTableAttributesObserver = 0;
}

PyMethodDef *
PyColorTableAttributes_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return ColorTableAttributesMethods;
}

bool
PyColorTableAttributes_Check(PyObject *obj)
{
    return (obj->ob_type == &ColorTableAttributesType);
}

ColorTableAttributes *
PyColorTableAttributes_FromPyObject(PyObject *obj)
{
    ColorTableAttributesObject *obj2 = (ColorTableAttributesObject *)obj;
    return obj2->data;
}

PyObject *
PyColorTableAttributes_New()
{
    return NewColorTableAttributes(0);
}

PyObject *
PyColorTableAttributes_Wrap(const ColorTableAttributes *attr)
{
    return WrapColorTableAttributes(attr);
}

void
PyColorTableAttributes_SetParent(PyObject *obj, PyObject *parent)
{
    ColorTableAttributesObject *obj2 = (ColorTableAttributesObject *)obj;
    obj2->parent = parent;
}

void
PyColorTableAttributes_SetDefaults(const ColorTableAttributes *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new ColorTableAttributes(*atts);
}

