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

// ****************************************************************************
// Module: PyLightAttributes
//
// Purpose: 
//   This class is a light in a light list.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

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

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

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

    if(atts->GetEnabledFlag())
        SNPRINTF(tmpStr, 1000, "%senabledFlag = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%senabledFlag = 0\n", prefix);
    str += tmpStr;
    const char *type_names = "Ambient, Object, Camera";
    switch (atts->GetType())
    {
      case LightAttributes::Ambient:
          SNPRINTF(tmpStr, 1000, "%stype = %sAmbient  # %s\n", prefix, prefix, type_names);
          str += tmpStr;
          break;
      case LightAttributes::Object:
          SNPRINTF(tmpStr, 1000, "%stype = %sObject  # %s\n", prefix, prefix, type_names);
          str += tmpStr;
          break;
      case LightAttributes::Camera:
          SNPRINTF(tmpStr, 1000, "%stype = %sCamera  # %s\n", prefix, prefix, type_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    {   const double *direction = atts->GetDirection();
        SNPRINTF(tmpStr, 1000, "%sdirection = (", prefix);
        str += tmpStr;
        for(int i = 0; i < 3; ++i)
        {
            SNPRINTF(tmpStr, 1000, "%g", direction[i]);
            str += tmpStr;
            if(i < 2)
            {
                SNPRINTF(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        SNPRINTF(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    const unsigned char *color = atts->GetColor().GetColor();
    SNPRINTF(tmpStr, 1000, "%scolor = (%d, %d, %d, %d)\n", prefix, int(color[0]), int(color[1]), int(color[2]), int(color[3]));
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%sbrightness = %g\n", prefix, atts->GetBrightness());
    str += tmpStr;
    return str;
}

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

/*static*/ PyObject *
LightAttributes_SetEnabledFlag(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

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

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

    Py_INCREF(Py_None);
    return Py_None;
}

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

/*static*/ PyObject *
LightAttributes_SetType(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

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

    // Set the type in the object.
    if(ival >= 0 && ival < 3)
        obj->data->SetType(LightAttributes::LightType(ival));
    else
    {
        fprintf(stderr, "An invalid type value was given. "
                        "Valid values are in the range of [0,2]. "
                        "You can also use the following names: "
                        "Ambient, Object, Camera.");
        return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

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

/*static*/ PyObject *
LightAttributes_SetDirection(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    double *dvals = obj->data->GetDirection();
    if(!PyArg_ParseTuple(args, "ddd", &dvals[0], &dvals[1], &dvals[2]))
    {
        PyObject     *tuple;
        if(!PyArg_ParseTuple(args, "O", &tuple))
            return NULL;

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

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

    // Mark the direction in the object as modified.
    obj->data->SelectDirection();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetDirection(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    // Allocate a tuple the with enough entries to hold the direction.
    PyObject *retval = PyTuple_New(3);
    const double *direction = obj->data->GetDirection();
    for(int i = 0; i < 3; ++i)
        PyTuple_SET_ITEM(retval, i, PyFloat_FromDouble(direction[i]));
    return retval;
}

/*static*/ PyObject *
LightAttributes_SetColor(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    int c[4];
    if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3]))
    {
        c[3] = 255;
        if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2]))
        {
            double dr, dg, db, da;
            if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = int(da);
            }
            else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = 255;
            }
            else
            {
                PyObject *tuple = NULL;
                if(!PyArg_ParseTuple(args, "O", &tuple))
                    return NULL;

                if(!PyTuple_Check(tuple))
                    return NULL;

                // Make sure that the tuple is the right size.
                if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4)
                    return NULL;

                // Make sure that all elements in the tuple are ints.
                for(int i = 0; i < PyTuple_Size(tuple); ++i)
                {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i);
                    if(PyInt_Check(item))
                        c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i)));
                    else if(PyFloat_Check(item))
                        c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i)));
                    else
                        return NULL;
                }
            }
        }
        PyErr_Clear();
    }

    // Set the color in the object.
    ColorAttribute ca(c[0], c[1], c[2], c[3]);
    obj->data->SetColor(ca);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetColor(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    // Allocate a tuple the with enough entries to hold the color.
    PyObject *retval = PyTuple_New(4);
    const unsigned char *color = obj->data->GetColor().GetColor();
    PyTuple_SET_ITEM(retval, 0, PyInt_FromLong(long(color[0])));
    PyTuple_SET_ITEM(retval, 1, PyInt_FromLong(long(color[1])));
    PyTuple_SET_ITEM(retval, 2, PyInt_FromLong(long(color[2])));
    PyTuple_SET_ITEM(retval, 3, PyInt_FromLong(long(color[3])));
    return retval;
}

/*static*/ PyObject *
LightAttributes_SetBrightness(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    double dval;
    if(!PyArg_ParseTuple(args, "d", &dval))
        return NULL;

    // Set the brightness in the object.
    obj->data->SetBrightness(dval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetBrightness(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    PyObject *retval = PyFloat_FromDouble(obj->data->GetBrightness());
    return retval;
}



PyMethodDef PyLightAttributes_methods[LIGHTATTRIBUTES_NMETH] = {
    {"Notify", LightAttributes_Notify, METH_VARARGS},
    {"SetEnabledFlag", LightAttributes_SetEnabledFlag, METH_VARARGS},
    {"GetEnabledFlag", LightAttributes_GetEnabledFlag, METH_VARARGS},
    {"SetType", LightAttributes_SetType, METH_VARARGS},
    {"GetType", LightAttributes_GetType, METH_VARARGS},
    {"SetDirection", LightAttributes_SetDirection, METH_VARARGS},
    {"GetDirection", LightAttributes_GetDirection, METH_VARARGS},
    {"SetColor", LightAttributes_SetColor, METH_VARARGS},
    {"GetColor", LightAttributes_GetColor, METH_VARARGS},
    {"SetBrightness", LightAttributes_SetBrightness, METH_VARARGS},
    {"GetBrightness", LightAttributes_GetBrightness, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

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

static int
LightAttributes_compare(PyObject *v, PyObject *w)
{
    LightAttributes *a = ((LightAttributesObject *)v)->data;
    LightAttributes *b = ((LightAttributesObject *)w)->data;
    return (*a == *b) ? 0 : -1;
}

PyObject *
PyLightAttributes_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "enabledFlag") == 0)
        return LightAttributes_GetEnabledFlag(self, NULL);
    if(strcmp(name, "type") == 0)
        return LightAttributes_GetType(self, NULL);
    if(strcmp(name, "Ambient") == 0)
        return PyInt_FromLong(long(LightAttributes::Ambient));
    if(strcmp(name, "Object") == 0)
        return PyInt_FromLong(long(LightAttributes::Object));
    if(strcmp(name, "Camera") == 0)
        return PyInt_FromLong(long(LightAttributes::Camera));

    if(strcmp(name, "direction") == 0)
        return LightAttributes_GetDirection(self, NULL);
    if(strcmp(name, "color") == 0)
        return LightAttributes_GetColor(self, NULL);
    if(strcmp(name, "brightness") == 0)
        return LightAttributes_GetBrightness(self, NULL);

    return Py_FindMethod(PyLightAttributes_methods, self, name);
}

int
PyLightAttributes_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, "enabledFlag") == 0)
        obj = LightAttributes_SetEnabledFlag(self, tuple);
    else if(strcmp(name, "type") == 0)
        obj = LightAttributes_SetType(self, tuple);
    else if(strcmp(name, "direction") == 0)
        obj = LightAttributes_SetDirection(self, tuple);
    else if(strcmp(name, "color") == 0)
        obj = LightAttributes_SetColor(self, tuple);
    else if(strcmp(name, "brightness") == 0)
        obj = LightAttributes_SetBrightness(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
LightAttributes_print(PyObject *v, FILE *fp, int flags)
{
    LightAttributesObject *obj = (LightAttributesObject *)v;
    fprintf(fp, "%s", PyLightAttributes_ToString(obj->data, "").c_str());
    return 0;
}

PyObject *
LightAttributes_str(PyObject *v)
{
    LightAttributesObject *obj = (LightAttributesObject *)v;
    return PyString_FromString(PyLightAttributes_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 *LightAttributes_Purpose = "This class is a light in a light list.";
#else
static char *LightAttributes_Purpose = "This class is a light in a light list.";
#endif

//
// The type description structure
//
static PyTypeObject LightAttributesType =
{
    //
    // Type header
    //
    PyObject_HEAD_INIT(&PyType_Type)
    0,                                   // ob_size
    "LightAttributes",                    // tp_name
    sizeof(LightAttributesObject),        // tp_basicsize
    0,                                   // tp_itemsize
    //
    // Standard methods
    //
    (destructor)LightAttributes_dealloc,  // tp_dealloc
    (printfunc)LightAttributes_print,     // tp_print
    (getattrfunc)PyLightAttributes_getattr, // tp_getattr
    (setattrfunc)PyLightAttributes_setattr, // tp_setattr
    (cmpfunc)LightAttributes_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)LightAttributes_str,        // tp_str
    0,                                   // tp_getattro
    0,                                   // tp_setattro
    0,                                   // tp_as_buffer
    Py_TPFLAGS_CHECKTYPES,               // tp_flags
    LightAttributes_Purpose,              // tp_doc
    0,                                   // tp_traverse
    0,                                   // tp_clear
    0,                                   // tp_richcompare
    0                                    // tp_weaklistoffset
};

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

static LightAttributes *defaultAtts = 0;
static LightAttributes *currentAtts = 0;

static PyObject *
NewLightAttributes(int useCurrent)
{
    LightAttributesObject *newObject;
    newObject = PyObject_NEW(LightAttributesObject, &LightAttributesType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new LightAttributes(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new LightAttributes(*defaultAtts);
    else
        newObject->data = new LightAttributes;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapLightAttributes(const LightAttributes *attr)
{
    LightAttributesObject *newObject;
    newObject = PyObject_NEW(LightAttributesObject, &LightAttributesType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (LightAttributes *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

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

PyObject *
LightAttributes_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 *)NewLightAttributes(useCurrent);
}

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

static Observer *LightAttributesObserver = 0;

std::string
PyLightAttributes_GetLogString()
{
    std::string s("LightAtts = LightAttributes()\n");
    if(currentAtts != 0)
        s += PyLightAttributes_ToString(currentAtts, "LightAtts.");
    return s;
}

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

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

void
PyLightAttributes_StartUp(LightAttributes *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyLightAttributes_SetDefaults(subj);

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

}

void
PyLightAttributes_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete LightAttributesObserver;
    LightAttributesObserver = 0;
}

PyMethodDef *
PyLightAttributes_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return LightAttributesMethods;
}

bool
PyLightAttributes_Check(PyObject *obj)
{
    return (obj->ob_type == &LightAttributesType);
}

LightAttributes *
PyLightAttributes_FromPyObject(PyObject *obj)
{
    LightAttributesObject *obj2 = (LightAttributesObject *)obj;
    return obj2->data;
}

PyObject *
PyLightAttributes_New()
{
    return NewLightAttributes(0);
}

PyObject *
PyLightAttributes_Wrap(const LightAttributes *attr)
{
    return WrapLightAttributes(attr);
}

void
PyLightAttributes_SetParent(PyObject *obj, PyObject *parent)
{
    LightAttributesObject *obj2 = (LightAttributesObject *)obj;
    obj2->parent = parent;
}

void
PyLightAttributes_SetDefaults(const LightAttributes *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new LightAttributes(*atts);
}

