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

// ****************************************************************************
// Module: PyPlotList
//
// Purpose: 
//   This class contains a list of plots.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

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

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

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

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

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

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

    return retval;
}

PyObject *
PlotList_GetNumPlots(PyObject *self, PyObject *args)
{
    PlotListObject *obj = (PlotListObject *)self;
    return PyInt_FromLong((long)obj->data->GetPlots().size());
}

PyObject *
PlotList_AddPlots(PyObject *self, PyObject *args)
{
    PlotListObject *obj = (PlotListObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PyPlot_Check(element))
    {
        char msg[400] = {'\0'};
        SNPRINTF(msg, 400, "The PlotList::AddPlots method only accepts Plot objects.");
        PyErr_SetString(PyExc_TypeError, msg);
        return NULL;
    }
    Plot *newData = PyPlot_FromPyObject(element);
    obj->data->AddPlots(*newData);
    obj->data->SelectPlots();
    Py_INCREF(Py_None);
    return Py_None;
}

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

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

    return PlotList_Remove_One_Plots(self, index);
}

PyObject *
PlotList_ClearPlots(PyObject *self, PyObject *args)
{
    PlotListObject *obj = (PlotListObject *)self;
    int n = obj->data->GetNumPlots();
    for(int i = 0; i < n; ++i)
    {
        PlotList_Remove_One_Plots(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}



PyMethodDef PyPlotList_methods[PLOTLIST_NMETH] = {
    {"Notify", PlotList_Notify, METH_VARARGS},
    {"GetPlots", PlotList_GetPlots, METH_VARARGS},
    {"GetNumPlots", PlotList_GetNumPlots, METH_VARARGS},
    {"AddPlots", PlotList_AddPlots, METH_VARARGS},
    {"RemovePlots", PlotList_RemovePlots, METH_VARARGS},
    {"ClearPlots", PlotList_ClearPlots, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

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

static int
PlotList_compare(PyObject *v, PyObject *w)
{
    PlotList *a = ((PlotListObject *)v)->data;
    PlotList *b = ((PlotListObject *)w)->data;
    return (*a == *b) ? 0 : -1;
}

PyObject *
PyPlotList_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "plots") == 0)
        return PlotList_GetPlots(self, NULL);

    return Py_FindMethod(PyPlotList_methods, self, name);
}

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

PyObject *
PlotList_str(PyObject *v)
{
    PlotListObject *obj = (PlotListObject *)v;
    return PyString_FromString(PyPlotList_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 *PlotList_Purpose = "This class contains a list of plots.";
#else
static char *PlotList_Purpose = "This class contains a list of plots.";
#endif

//
// The type description structure
//
static PyTypeObject PlotListType =
{
    //
    // Type header
    //
    PyObject_HEAD_INIT(&PyType_Type)
    0,                                   // ob_size
    "PlotList",                    // tp_name
    sizeof(PlotListObject),        // tp_basicsize
    0,                                   // tp_itemsize
    //
    // Standard methods
    //
    (destructor)PlotList_dealloc,  // tp_dealloc
    (printfunc)PlotList_print,     // tp_print
    (getattrfunc)PyPlotList_getattr, // tp_getattr
    (setattrfunc)PyPlotList_setattr, // tp_setattr
    (cmpfunc)PlotList_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)PlotList_str,        // tp_str
    0,                                   // tp_getattro
    0,                                   // tp_setattro
    0,                                   // tp_as_buffer
    Py_TPFLAGS_CHECKTYPES,               // tp_flags
    PlotList_Purpose,              // tp_doc
    0,                                   // tp_traverse
    0,                                   // tp_clear
    0,                                   // tp_richcompare
    0                                    // tp_weaklistoffset
};

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

static PlotList *defaultAtts = 0;
static PlotList *currentAtts = 0;

static PyObject *
NewPlotList(int useCurrent)
{
    PlotListObject *newObject;
    newObject = PyObject_NEW(PlotListObject, &PlotListType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new PlotList(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new PlotList(*defaultAtts);
    else
        newObject->data = new PlotList;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapPlotList(const PlotList *attr)
{
    PlotListObject *newObject;
    newObject = PyObject_NEW(PlotListObject, &PlotListType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (PlotList *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

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

PyObject *
PlotList_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 *)NewPlotList(useCurrent);
}

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

static Observer *PlotListObserver = 0;

std::string
PyPlotList_GetLogString()
{
    std::string s("PlotList = PlotList()\n");
    if(currentAtts != 0)
        s += PyPlotList_ToString(currentAtts, "PlotList.");
    return s;
}

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

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

void
PyPlotList_StartUp(PlotList *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyPlotList_SetDefaults(subj);

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

}

void
PyPlotList_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete PlotListObserver;
    PlotListObserver = 0;
}

PyMethodDef *
PyPlotList_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return PlotListMethods;
}

bool
PyPlotList_Check(PyObject *obj)
{
    return (obj->ob_type == &PlotListType);
}

PlotList *
PyPlotList_FromPyObject(PyObject *obj)
{
    PlotListObject *obj2 = (PlotListObject *)obj;
    return obj2->data;
}

PyObject *
PyPlotList_New()
{
    return NewPlotList(0);
}

PyObject *
PyPlotList_Wrap(const PlotList *attr)
{
    return WrapPlotList(attr);
}

void
PyPlotList_SetParent(PyObject *obj, PyObject *parent)
{
    PlotListObject *obj2 = (PlotListObject *)obj;
    obj2->parent = parent;
}

void
PyPlotList_SetDefaults(const PlotList *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new PlotList(*atts);
}

