/*****************************************************************************
*
* 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 <PyViewerClientInformation.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <snprintf.h>
#include <PyViewerClientInformationElement.h>

// ****************************************************************************
// Module: PyViewerClientInformation
//
// Purpose: 
//   This class contains information generated for each client
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

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

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

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

    { // new scope
        int index = 0;
        // Create string representation of vars from atts.
        for(AttributeGroupVector::const_iterator pos = atts->GetVars().begin(); pos != atts->GetVars().end(); ++pos, ++index)
        {
            const ViewerClientInformationElement *current = (const ViewerClientInformationElement *)(*pos);
            SNPRINTF(tmpStr, 1000, "GetVars(%d).", index);
            std::string objPrefix(prefix + std::string(tmpStr));
            str += PyViewerClientInformationElement_ToString(current, objPrefix.c_str());
        }
        if(index == 0)
            str += "#vars does not contain any ViewerClientInformationElement objects.\n";
    }
    {   const stringVector &supportedFormats = atts->GetSupportedFormats();
        SNPRINTF(tmpStr, 1000, "%ssupportedFormats = (", prefix);
        str += tmpStr;
        for(size_t i = 0; i < supportedFormats.size(); ++i)
        {
            SNPRINTF(tmpStr, 1000, "\"%s\"", supportedFormats[i].c_str());
            str += tmpStr;
            if(i < supportedFormats.size() - 1)
            {
                SNPRINTF(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        SNPRINTF(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    return str;
}

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

/*static*/ PyObject *
ViewerClientInformation_GetVars(PyObject *self, PyObject *args)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)self;
    int index;
    if(!PyArg_ParseTuple(args, "i", &index))
        return NULL;
    if(index < 0 || (size_t)index >= obj->data->GetVars().size())
    {
        char msg[400] = {'\0'};
        if(obj->data->GetVars().size() == 0)
            SNPRINTF(msg, 400, "In ViewerClientInformation::GetVars : The index %d is invalid because vars is empty.", index);
        else
            SNPRINTF(msg, 400, "In ViewerClientInformation::GetVars : The index %d is invalid. Use index values in: [0, %ld).",  index, obj->data->GetVars().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 = PyViewerClientInformationElement_Wrap(&obj->data->GetVars(index));
    // Set the object's parent so the reference to the parent can be decref'd
    // when the child goes out of scope.
    PyViewerClientInformationElement_SetParent(retval, self);

    return retval;
}

PyObject *
ViewerClientInformation_GetNumVars(PyObject *self, PyObject *args)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)self;
    return PyInt_FromLong((long)obj->data->GetVars().size());
}

PyObject *
ViewerClientInformation_AddVars(PyObject *self, PyObject *args)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PyViewerClientInformationElement_Check(element))
    {
        char msg[400] = {'\0'};
        SNPRINTF(msg, 400, "The ViewerClientInformation::AddVars method only accepts ViewerClientInformationElement objects.");
        PyErr_SetString(PyExc_TypeError, msg);
        return NULL;
    }
    ViewerClientInformationElement *newData = PyViewerClientInformationElement_FromPyObject(element);
    obj->data->AddVars(*newData);
    obj->data->SelectVars();
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
ViewerClientInformation_Remove_One_Vars(PyObject *self, int index)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)self;
    // Remove in the AttributeGroupVector instead of calling RemoveVars() because we don't want to delete the object; just remove it.
    AttributeGroupVector &atts = obj->data->GetVars();
    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->SelectVars();
    Py_INCREF(Py_None);
    return Py_None;
}

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

    return ViewerClientInformation_Remove_One_Vars(self, index);
}

PyObject *
ViewerClientInformation_ClearVars(PyObject *self, PyObject *args)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)self;
    int n = obj->data->GetNumVars();
    for(int i = 0; i < n; ++i)
    {
        ViewerClientInformation_Remove_One_Vars(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ViewerClientInformation_SetSupportedFormats(PyObject *self, PyObject *args)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)self;

    stringVector  &vec = obj->data->GetSupportedFormats();
    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 supportedFormats in the object as modified.
    obj->data->SelectSupportedFormats();

    Py_INCREF(Py_None);
    return Py_None;
}

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



PyMethodDef PyViewerClientInformation_methods[VIEWERCLIENTINFORMATION_NMETH] = {
    {"Notify", ViewerClientInformation_Notify, METH_VARARGS},
    {"GetVars", ViewerClientInformation_GetVars, METH_VARARGS},
    {"GetNumVars", ViewerClientInformation_GetNumVars, METH_VARARGS},
    {"AddVars", ViewerClientInformation_AddVars, METH_VARARGS},
    {"RemoveVars", ViewerClientInformation_RemoveVars, METH_VARARGS},
    {"ClearVars", ViewerClientInformation_ClearVars, METH_VARARGS},
    {"SetSupportedFormats", ViewerClientInformation_SetSupportedFormats, METH_VARARGS},
    {"GetSupportedFormats", ViewerClientInformation_GetSupportedFormats, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

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

static int
ViewerClientInformation_compare(PyObject *v, PyObject *w)
{
    ViewerClientInformation *a = ((ViewerClientInformationObject *)v)->data;
    ViewerClientInformation *b = ((ViewerClientInformationObject *)w)->data;
    return (*a == *b) ? 0 : -1;
}

PyObject *
PyViewerClientInformation_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "vars") == 0)
        return ViewerClientInformation_GetVars(self, NULL);
    if(strcmp(name, "supportedFormats") == 0)
        return ViewerClientInformation_GetSupportedFormats(self, NULL);

    return Py_FindMethod(PyViewerClientInformation_methods, self, name);
}

int
PyViewerClientInformation_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, "supportedFormats") == 0)
        obj = ViewerClientInformation_SetSupportedFormats(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
ViewerClientInformation_print(PyObject *v, FILE *fp, int flags)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)v;
    fprintf(fp, "%s", PyViewerClientInformation_ToString(obj->data, "").c_str());
    return 0;
}

PyObject *
ViewerClientInformation_str(PyObject *v)
{
    ViewerClientInformationObject *obj = (ViewerClientInformationObject *)v;
    return PyString_FromString(PyViewerClientInformation_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 *ViewerClientInformation_Purpose = "This class contains information generated for each client";
#else
static char *ViewerClientInformation_Purpose = "This class contains information generated for each client";
#endif

//
// The type description structure
//
static PyTypeObject ViewerClientInformationType =
{
    //
    // Type header
    //
    PyObject_HEAD_INIT(&PyType_Type)
    0,                                   // ob_size
    "ViewerClientInformation",                    // tp_name
    sizeof(ViewerClientInformationObject),        // tp_basicsize
    0,                                   // tp_itemsize
    //
    // Standard methods
    //
    (destructor)ViewerClientInformation_dealloc,  // tp_dealloc
    (printfunc)ViewerClientInformation_print,     // tp_print
    (getattrfunc)PyViewerClientInformation_getattr, // tp_getattr
    (setattrfunc)PyViewerClientInformation_setattr, // tp_setattr
    (cmpfunc)ViewerClientInformation_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)ViewerClientInformation_str,        // tp_str
    0,                                   // tp_getattro
    0,                                   // tp_setattro
    0,                                   // tp_as_buffer
    Py_TPFLAGS_CHECKTYPES,               // tp_flags
    ViewerClientInformation_Purpose,              // tp_doc
    0,                                   // tp_traverse
    0,                                   // tp_clear
    0,                                   // tp_richcompare
    0                                    // tp_weaklistoffset
};

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

static ViewerClientInformation *defaultAtts = 0;
static ViewerClientInformation *currentAtts = 0;

static PyObject *
NewViewerClientInformation(int useCurrent)
{
    ViewerClientInformationObject *newObject;
    newObject = PyObject_NEW(ViewerClientInformationObject, &ViewerClientInformationType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new ViewerClientInformation(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new ViewerClientInformation(*defaultAtts);
    else
        newObject->data = new ViewerClientInformation;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapViewerClientInformation(const ViewerClientInformation *attr)
{
    ViewerClientInformationObject *newObject;
    newObject = PyObject_NEW(ViewerClientInformationObject, &ViewerClientInformationType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (ViewerClientInformation *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

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

PyObject *
ViewerClientInformation_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 *)NewViewerClientInformation(useCurrent);
}

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

static Observer *ViewerClientInformationObserver = 0;

std::string
PyViewerClientInformation_GetLogString()
{
    std::string s("ViewerClientInformation = ViewerClientInformation()\n");
    if(currentAtts != 0)
        s += PyViewerClientInformation_ToString(currentAtts, "ViewerClientInformation.");
    return s;
}

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

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

void
PyViewerClientInformation_StartUp(ViewerClientInformation *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyViewerClientInformation_SetDefaults(subj);

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

}

void
PyViewerClientInformation_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete ViewerClientInformationObserver;
    ViewerClientInformationObserver = 0;
}

PyMethodDef *
PyViewerClientInformation_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return ViewerClientInformationMethods;
}

bool
PyViewerClientInformation_Check(PyObject *obj)
{
    return (obj->ob_type == &ViewerClientInformationType);
}

ViewerClientInformation *
PyViewerClientInformation_FromPyObject(PyObject *obj)
{
    ViewerClientInformationObject *obj2 = (ViewerClientInformationObject *)obj;
    return obj2->data;
}

PyObject *
PyViewerClientInformation_New()
{
    return NewViewerClientInformation(0);
}

PyObject *
PyViewerClientInformation_Wrap(const ViewerClientInformation *attr)
{
    return WrapViewerClientInformation(attr);
}

void
PyViewerClientInformation_SetParent(PyObject *obj, PyObject *parent)
{
    ViewerClientInformationObject *obj2 = (ViewerClientInformationObject *)obj;
    obj2->parent = parent;
}

void
PyViewerClientInformation_SetDefaults(const ViewerClientInformation *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new ViewerClientInformation(*atts);
}

