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

// ****************************************************************************
// Module: PyExpressionList
//
// Purpose: 
//   This class contains a list of expressions and some functions to manipulate them.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

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

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

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

    { // new scope
        int index = 0;
        // Create string representation of expressions from atts.
        for(AttributeGroupVector::const_iterator pos = atts->GetExpressions().begin(); pos != atts->GetExpressions().end(); ++pos, ++index)
        {
            const Expression *current = (const Expression *)(*pos);
            SNPRINTF(tmpStr, 1000, "GetExpressions(%d).", index);
            std::string objPrefix(prefix + std::string(tmpStr));
            str += PyExpression_ToString(current, objPrefix.c_str());
        }
        if(index == 0)
            str += "#expressions does not contain any Expression objects.\n";
    }
    return str;
}

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

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

    return retval;
}

PyObject *
ExpressionList_GetNumExpressions(PyObject *self, PyObject *args)
{
    ExpressionListObject *obj = (ExpressionListObject *)self;
    return PyInt_FromLong((long)obj->data->GetExpressions().size());
}

PyObject *
ExpressionList_AddExpressions(PyObject *self, PyObject *args)
{
    ExpressionListObject *obj = (ExpressionListObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PyExpression_Check(element))
    {
        char msg[400] = {'\0'};
        SNPRINTF(msg, 400, "The ExpressionList::AddExpressions method only accepts Expression objects.");
        PyErr_SetString(PyExc_TypeError, msg);
        return NULL;
    }
    Expression *newData = PyExpression_FromPyObject(element);
    obj->data->AddExpressions(*newData);
    obj->data->SelectExpressions();
    Py_INCREF(Py_None);
    return Py_None;
}

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

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

    return ExpressionList_Remove_One_Expressions(self, index);
}

PyObject *
ExpressionList_ClearExpressions(PyObject *self, PyObject *args)
{
    ExpressionListObject *obj = (ExpressionListObject *)self;
    int n = obj->data->GetNumExpressions();
    for(int i = 0; i < n; ++i)
    {
        ExpressionList_Remove_One_Expressions(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}



PyMethodDef PyExpressionList_methods[EXPRESSIONLIST_NMETH] = {
    {"Notify", ExpressionList_Notify, METH_VARARGS},
    {"GetExpressions", ExpressionList_GetExpressions, METH_VARARGS},
    {"GetNumExpressions", ExpressionList_GetNumExpressions, METH_VARARGS},
    {"AddExpressions", ExpressionList_AddExpressions, METH_VARARGS},
    {"RemoveExpressions", ExpressionList_RemoveExpressions, METH_VARARGS},
    {"ClearExpressions", ExpressionList_ClearExpressions, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

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

static int
ExpressionList_compare(PyObject *v, PyObject *w)
{
    ExpressionList *a = ((ExpressionListObject *)v)->data;
    ExpressionList *b = ((ExpressionListObject *)w)->data;
    return (*a == *b) ? 0 : -1;
}

PyObject *
PyExpressionList_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "expressions") == 0)
        return ExpressionList_GetExpressions(self, NULL);

    return Py_FindMethod(PyExpressionList_methods, self, name);
}

int
PyExpressionList_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(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
ExpressionList_print(PyObject *v, FILE *fp, int flags)
{
    ExpressionListObject *obj = (ExpressionListObject *)v;
    fprintf(fp, "%s", PyExpressionList_ToString(obj->data, "").c_str());
    return 0;
}

PyObject *
ExpressionList_str(PyObject *v)
{
    ExpressionListObject *obj = (ExpressionListObject *)v;
    return PyString_FromString(PyExpressionList_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 *ExpressionList_Purpose = "This class contains a list of expressions and some functions to manipulate them.";
#else
static char *ExpressionList_Purpose = "This class contains a list of expressions and some functions to manipulate them.";
#endif

//
// The type description structure
//
static PyTypeObject ExpressionListType =
{
    //
    // Type header
    //
    PyObject_HEAD_INIT(&PyType_Type)
    0,                                   // ob_size
    "ExpressionList",                    // tp_name
    sizeof(ExpressionListObject),        // tp_basicsize
    0,                                   // tp_itemsize
    //
    // Standard methods
    //
    (destructor)ExpressionList_dealloc,  // tp_dealloc
    (printfunc)ExpressionList_print,     // tp_print
    (getattrfunc)PyExpressionList_getattr, // tp_getattr
    (setattrfunc)PyExpressionList_setattr, // tp_setattr
    (cmpfunc)ExpressionList_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)ExpressionList_str,        // tp_str
    0,                                   // tp_getattro
    0,                                   // tp_setattro
    0,                                   // tp_as_buffer
    Py_TPFLAGS_CHECKTYPES,               // tp_flags
    ExpressionList_Purpose,              // tp_doc
    0,                                   // tp_traverse
    0,                                   // tp_clear
    0,                                   // tp_richcompare
    0                                    // tp_weaklistoffset
};

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

static ExpressionList *defaultAtts = 0;
static ExpressionList *currentAtts = 0;

static PyObject *
NewExpressionList(int useCurrent)
{
    ExpressionListObject *newObject;
    newObject = PyObject_NEW(ExpressionListObject, &ExpressionListType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new ExpressionList(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new ExpressionList(*defaultAtts);
    else
        newObject->data = new ExpressionList;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapExpressionList(const ExpressionList *attr)
{
    ExpressionListObject *newObject;
    newObject = PyObject_NEW(ExpressionListObject, &ExpressionListType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (ExpressionList *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

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

PyObject *
ExpressionList_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 *)NewExpressionList(useCurrent);
}

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

static Observer *ExpressionListObserver = 0;

std::string
PyExpressionList_GetLogString()
{
    std::string s("ExpressionList = ExpressionList()\n");
    if(currentAtts != 0)
        s += PyExpressionList_ToString(currentAtts, "ExpressionList.");
    return s;
}

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

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

void
PyExpressionList_StartUp(ExpressionList *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyExpressionList_SetDefaults(subj);

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

}

void
PyExpressionList_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete ExpressionListObserver;
    ExpressionListObserver = 0;
}

PyMethodDef *
PyExpressionList_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return ExpressionListMethods;
}

bool
PyExpressionList_Check(PyObject *obj)
{
    return (obj->ob_type == &ExpressionListType);
}

ExpressionList *
PyExpressionList_FromPyObject(PyObject *obj)
{
    ExpressionListObject *obj2 = (ExpressionListObject *)obj;
    return obj2->data;
}

PyObject *
PyExpressionList_New()
{
    return NewExpressionList(0);
}

PyObject *
PyExpressionList_Wrap(const ExpressionList *attr)
{
    return WrapExpressionList(attr);
}

void
PyExpressionList_SetParent(PyObject *obj, PyObject *parent)
{
    ExpressionListObject *obj2 = (ExpressionListObject *)obj;
    obj2->parent = parent;
}

void
PyExpressionList_SetDefaults(const ExpressionList *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new ExpressionList(*atts);
}

