/*
 * DynamicFields.cpp
 *
 * Copyright (C) 2006 J. "MUFTI" Scheurichx
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program (see the file "COPYING" for details); if 
 * not, write to the Free Software Foundation, Inc., 675 Mass Ave, 
 * Cambridge, MA 02139, USA.
 */

#include "DynamicFieldsNode.h"
#include "DuneApp.h"
#include "Scene.h"
#include "Field.h"
#include "ExposedField.h"
#include "EventIn.h"
#include "EventOut.h"
#include "RouteCommand.h"
#include "UnRouteCommand.h"
#include "NodeScript.h"

void DynamicFieldsNode::initialise(void)
{
    _routeList = NULL;
}

int DynamicFieldsNode::write(int f, int indent)
{
    int flags = _scene->getWriteFlags();
    TheApp->checkSelectionLinenumberCounting(_scene, this);
    RET_ONERROR( indentf(f, indent) )
    if (getFlag(NODE_FLAG_DEFED)) {
        RET_ONERROR( mywritestr(f ,"USE ") )
        RET_ONERROR( mywritestr(f ,(const char *) _name) )
        RET_ONERROR( mywritestr(f ,"\n") )
        TheApp->incSelectionLinenumber();
    } else {
        if (needsDEF()) {
            if (!_name[0]) _scene->generateUniqueNodeName(this);
                RET_ONERROR( mywritestr(f,"DEF ") )
                RET_ONERROR( mywritestr(f, (const char *) _name) )
                RET_ONERROR( mywritestr(f," ") )
            }
        setFlag(NODE_FLAG_DEFED);
        RET_ONERROR( mywritestr(f, getProto()->getName(::isX3d(flags))) )
        RET_ONERROR( mywritestr(f, " ") )
        if (!TheApp->GetkrFormating()) {
            RET_ONERROR( mywritestr(f, "\n") )
            TheApp->incSelectionLinenumber();
            RET_ONERROR( indentf(f, indent + TheApp->GetIndent()) )
        }
        RET_ONERROR( mywritestr(f, "{\n") )
        TheApp->incSelectionLinenumber();
        RET_ONERROR( writeEvents(f, indent + TheApp->GetIndent()) )
        RET_ONERROR( writeFields(f, indent + TheApp->GetIndent()) )
        if (!TheApp->GetkrFormating())
            RET_ONERROR( indentf(f, indent + TheApp->GetIndent()) )
        else
            RET_ONERROR( indentf(f, indent) )
        RET_ONERROR( mywritestr(f, "}\n") )
        TheApp->incSelectionLinenumber();
        if (indent==0) {
            RET_ONERROR( mywritestr(f ,"\n") )
            TheApp->incSelectionLinenumber();
        }
        RET_ONERROR( writeRoutes(f, indent) )
        setFlag(NODE_FLAG_TOUCHED);
    }
    return(0);
}

int DynamicFieldsNode::writeXml(int f, int indent)
{
    if (getType() == VRML_SCRIPT) { 
        NodeScript *node = (NodeScript *) this;
        int i = 0;
        for (i = 0; i < _proto->getNumFields(); i++) {
            if (i == node->directOutput_Field())
                continue;
            if (i == node->mustEvaluate_Field())
                continue;
            if (i == node->url_Field())
                _proto->getField(i)->addFlags(FF_SCRIPT_URL);
            else
                _proto->getField(i)->addFlags(FF_IN_SCRIPT);
        }
        for (i = 0; i < _proto->getNumEventIns(); i++)
            _proto->getEventIn(i)->addFlags(FF_IN_SCRIPT);
        for (i = 0; i < _proto->getNumEventOuts(); i++)
            _proto->getEventOut(i)->addFlags(FF_IN_SCRIPT);
        
    }
    return NodeData::writeXml(f, indent);
}

int DynamicFieldsNode::writeField(int f, int indent, int fieldIndex)
{
    const char *oldBase = _scene->getURL();
    const char *newBase = _scene->getNewURL();
    bool tempSave = _scene->isTempSave();

    bool x3d = _scene->isX3d();

    Field *field = _proto->getField(fieldIndex);
    ExposedField *exposedField = field->getExposedField();
    FieldValue *value = _fields[fieldIndex];
    if ((field->getFlags() & FF_STATIC) || 
        (fieldIndex == _proto->metadata_Field())) {
        if (value && !value->equals(field->getDefault(x3d))) {
            RET_ONERROR( indentf(f, indent) )
            RET_ONERROR( mywritestr(f ,(const char *) field->getName(x3d)) )
            RET_ONERROR( mywritestr(f ," ") )
            if ((field->getFlags() & FF_URL) && (!TheApp->GetKeepURLs())) {
                value = rewriteField(value, oldBase, newBase);
                RET_ONERROR( value->write(f, indent) )
                if (!tempSave) {
                    setField(fieldIndex, value);
                } else {
                    delete value;
                }
            } else if (field->getFlags() & (FF_STATIC | FF_HIDDEN)) {
                RET_ONERROR( value->write(f, indent) )
            } else {
                RET_ONERROR( write(f, indent) )
            }
        }
    } else {
        Element *element = field;
        if (exposedField != NULL)
            element = exposedField;
        RET_ONERROR( indentf(f, indent) )
        RET_ONERROR( mywritestr(f, element->getElementName(x3d)) )
        RET_ONERROR( mywritestr(f, " ") )
        RET_ONERROR( mywritestr(f, typeEnumToString(element->getType())) ) 
        RET_ONERROR( mywritestr(f, " ") )
        RET_ONERROR( Node::writeField(f, 0, fieldIndex, true) )
    }
    return(0);
}

void incSelectionLinenumberOnMultilineMFString(MFString *mfstring)
{
    // count end of line characters in a multiline MFString like url in Script
    if (mfstring != NULL) {
        for (int i=0; i < mfstring->getSize() ; i++) {
            char* string = (char*) ((const char*) mfstring->getValue(i));
            while ((string=strchr(string, '\n')) !=NULL) {
                TheApp->incSelectionLinenumber();
                string++;
            }
        }
    }
}

int DynamicFieldsNode::writeFields(int f, int indent)
{
    if (!_proto) return(0);
    for (int i = 0; i < _numFields; i++) {
        RET_ONERROR( writeField(f, indent, i) )
        if (i == getMultilineMFStringField())
            incSelectionLinenumberOnMultilineMFString((MFString *) getField(i));
    }
    return(0);
}

int 
DynamicFieldsNode::writeEvents(int f, int indent)
{
    int i;

    if (!_proto) return(0);

    bool x3d = _scene->isX3d();

    for (i = 0; i < _numEventIns; i++) {
        EventIn *eventIn = _proto->getEventIn(i);
        if (eventIn->getFlags() & (FF_STATIC | FF_HIDDEN))
            continue; 
        ExposedField *exposedField = eventIn->getExposedField();
        if (exposedField && (exposedField->getFlags() & (FF_STATIC | FF_HIDDEN))
           )
            continue; 
        if (exposedField && !isPROTO())
            continue; 
        RET_ONERROR( indentf(f, indent) )
        RET_ONERROR( mywritestr(f, eventIn->getElementName(x3d)) )
        RET_ONERROR( mywritestr(f, " ") )
        RET_ONERROR( mywritestr(f, typeEnumToString(eventIn->getType())) ) 
        RET_ONERROR( mywritestr(f, " ") )
        RET_ONERROR( writeEventIn(f, 0, i, true) )
    }

    for (i = 0; i < _numEventOuts; i++) {
        EventOut *eventOut = _proto->getEventOut(i);
        if (eventOut->getFlags() & (FF_STATIC | FF_HIDDEN))
            continue; 
        ExposedField *exposedField = eventOut->getExposedField();
        if (exposedField && (exposedField->getFlags() & (FF_STATIC | FF_HIDDEN))
           )
            continue; 
        if (exposedField && !isPROTO())
            continue; 
        RET_ONERROR( indentf(f, indent) )
        RET_ONERROR( mywritestr(f, eventOut->getElementName(x3d)) )
        RET_ONERROR( mywritestr(f, " ") )
        RET_ONERROR( mywritestr(f, typeEnumToString(eventOut->getType())) ) 
        RET_ONERROR( mywritestr(f, " ") )
        RET_ONERROR( writeEventOut(f, 0, i, true) )
    }

    return(0);
}

//  When a eventIn is deleted, the routes must be updated.
//  Routes are handled via "sockets", a list which contain (for eventIns)
//  the node of source of a route and a integer index to the event/field 
//  of the source route

void DynamicFieldsNode::updateEventIn(int newIndex, int oldIndex)
{
     CommandList* deleteList = new CommandList();
     for (SocketList::Iterator *i = _inputs[oldIndex].first(); i != NULL; 
          i = i->next()) {
         RouteSocket outS = i->item();
         for (SocketList::Iterator *j = 
              outS.getNode()->getOutput(outS.getField()).first(); j != NULL; 
              j = j->next()) {
             RouteSocket inS = j->item();
             if ((inS.getNode() == this) && (inS.getField() == oldIndex)) {
                 // delete old route
                 deleteList->append(new UnRouteCommand(outS.getNode(), 
                                                       outS.getField(), 
                                                       this, oldIndex));
                 
                 // add new route to _routeList
                 if (!_routeList) _routeList = new CommandList();
                 _routeList->append(new RouteCommand(outS.getNode(), 
                                                     outS.getField(), 
                                                     this, newIndex));
             }
         }
     }
     _scene->execute(deleteList);
}

//  When a eventOut is deleted, the routes must be updated.
//  Routes are handled via "sockets", a list which contain (for eventOut)
//  the node of target of a route and a integer index to the event/field 
//  of the target route

void DynamicFieldsNode::updateEventOut(int newIndex, int oldIndex)
{
     CommandList* deleteList = new CommandList();
     for (SocketList::Iterator *i = _outputs[oldIndex].first(); i != NULL; 
          i = i->next()) {
         RouteSocket inS = i->item();
         for (SocketList::Iterator *j = inS.getNode()->getInput(inS.getField())
              .first(); j != NULL; j = j->next()) {
             RouteSocket outS = j->item();
             if ((outS.getNode() == this) && (outS.getField() == oldIndex)) {
                 // delete old route
                 deleteList->append(new UnRouteCommand(this, oldIndex,
                                                       inS.getNode(), 
                                                       inS.getField()));
                                                       
                 // add new route to _routeList
                 if (!_routeList) _routeList = new CommandList();
                 _routeList->append(new RouteCommand(this, newIndex,
                                                     inS.getNode(), 
                                                     inS.getField()));
             }
         }
     }
     _scene->execute(deleteList);
}

// since scripts can have dynamically-added fields, we need to update
// the node's fields after the script is defined.
// Same problem for the scriptinterfacebuilder (ScriptDialog) (add or delete)
//
// It is important, that only one item (field, eventIn or eventOut) can
// be added or deleted during this call of update.

void
DynamicFieldsNode::updateDynamicFields()
{
    bool x3d = _scene->isX3d();
    int i;

    int newNumFields = _proto->getNumFields();
    // add 
    if (_numFields < newNumFields) {
        FieldValue **newFields = new FieldValue *[newNumFields];
        for (i = 0; i < _numFields; i++) {
            newFields[i] = _fields[i];
        }
        for (i = _numFields; i < newNumFields; i++) {
            newFields[i] = _proto->getField(i)->getDefault(x3d);
            if (newFields[i])
                newFields[i]->ref();
        }

        // avoid delete of _fields[something]
        for (i = 0 ; i < _numFields ; i++)
            _fields[i] = NULL;
        delete [] _fields;
        _fields = newFields;
        _numFields = newNumFields;
    } else {
        // delete ?
        for (i = 0; i < _numFields; i++)
            if ((_proto->getField(i)->getFlags() & FF_DELETED) != 0) {
                // delete !
                newNumFields = _numFields-1;
                FieldValue **newFields = new FieldValue *[newNumFields];
                int newIndex=0;
                for (int j = 0; j < _numFields; j++)
                    if (j != i)
                        newFields[newIndex++] = _fields[j];
                _proto->_fields.remove(i);

                // avoid delete of _fields[something]
                for (i = 0 ; i < _numFields ; i++)
                    _fields[i] = NULL;
                delete [] _fields;
                _fields = newFields;
                _numFields = newNumFields;
                break;
            }
    }

    int newNumEventIns = _proto->getNumEventIns();
    // add 
    if (_numEventIns < newNumEventIns) {
        SocketList *newInputs = new SocketList[newNumEventIns];
        for (i = 0; i < _numEventIns; i++) {
            newInputs[i] = _inputs[i];
        }

        // avoid delete of _inputs[something]
        for (i = 0 ; i < _numEventIns ; i++)
            _inputs[i] = SocketList();
        delete [] _inputs;
        _inputs = newInputs;
        _numEventIns = newNumEventIns;
    } else {
        // delete ?
        for (i = 0; i < _numEventIns; i++)
            if ((_proto->getEventIn(i)->getFlags() & FF_DELETED) != 0) {
                // delete !
                newNumEventIns = _numEventIns-1;
                SocketList *newInputs = new SocketList[newNumEventIns];
                int newIndex=0;
                for (int j = 0; j < _numEventIns; j++) {
                    if (newIndex != j)
                        updateEventIn(newIndex, j);
                    if (j != i)
                        newInputs[newIndex++] = _inputs[j];
                }

                _proto->_eventIns.remove(i);

                // avoid delete of _inputs[something!=i]
                for (int k = 0 ; k < _numEventIns ; k++)
                    if (k != i)
                        _inputs[k] = SocketList();
                delete [] _inputs;
                _inputs = newInputs;
                _numEventIns = newNumEventIns;
                // execute addRouteCommands from updateEventIn()
                if (_routeList) _scene->execute(_routeList);
                _routeList = NULL;
                break;
            }
    }

    int newNumEventOuts = _proto->getNumEventOuts();
    // add 
    if (_numEventOuts < newNumEventOuts) {
        SocketList *newOutputs = new SocketList[newNumEventOuts];
        for (i = 0; i < _numEventOuts; i++) {
            newOutputs[i] = _outputs[i];
        }

        // avoid delete of _outputs[something]
        for (i = 0 ; i < _numEventOuts ; i++)
            _outputs[i] = SocketList();
        delete [] _outputs;
        _outputs = newOutputs;
        _numEventOuts = newNumEventOuts;
    } else {
        // delete ?
        for (i = 0; i < _numEventOuts; i++)
            if ((_proto->getEventOut(i)->getFlags() & FF_DELETED) != 0) {
                // delete !
                newNumEventOuts = _numEventOuts-1;
                SocketList *newOutputs = new SocketList[newNumEventOuts];
                int newIndex=0;
                for (int j = 0; j < _numEventOuts; j++) {
                    if (newIndex != j)
                        updateEventOut(newIndex, j);
                    if (j != i) 
                        newOutputs[newIndex++] = _outputs[j];
                }
                _proto->_eventOuts.remove(i);

                // avoid delete of _outputs[something!=i]
                for (int k = 0 ; k < _numEventOuts ; k++)
                    if (k != i)
                        _outputs[k] = SocketList();
                delete [] _outputs;
                _outputs = newOutputs;
                _numEventOuts = newNumEventOuts;
                // execute addRouteCommands from updateEventIn()
                if (_routeList) _scene->execute(_routeList);
                _routeList = NULL;
                break;
            }
    }
}

// collect array of dynamic field's, eventIn's and eventOut's
void
DynamicFieldsNode::buildInterfaceData(void) 
{
    int i;
    bool x3d = _scene->isX3d();
    _interface.resize(0);
    Proto* proto = getProto();
    if (proto == NULL)
        return;
    for (i=0; i < proto->getNumFields(); i++)
        if (!(proto->getField(i)->getFlags() && (FF_STATIC | FF_HIDDEN))) 
            _interface.append(new InterfaceData(EL_FIELD, i));
    for (i=0; i < proto->getNumEventOuts(); i++) {
        // ignore Exposedfields (eg. "url")
        bool isExposedField = false;
        for (int j=0; j < proto->_exposedFields.size(); j++) {
            MyString exposedName = 
                  mystrdup(proto->getExposedField(j)->getName(x3d));
            exposedName += "_changed";
            if (strcmp(proto->getEventOut(i)->getName(x3d), exposedName) == 0)
               isExposedField = true;
        }
        if (isExposedField) 
            continue;
        if (!(proto->getEventOut(i)->getFlags() && (FF_STATIC | FF_HIDDEN)))
            _interface.append(new InterfaceData(EL_EVENT_OUT, i));
    }
    for (i=0; i < proto->getNumEventIns(); i++) {
        // ignore Exposedfields (eg. "url")
        bool isExposedField = false;
        for (int j=0; j < proto->_exposedFields.size(); j++) {
            MyString exposedName = "set_";
            exposedName += proto->getExposedField(j)->getName(x3d);
            if (strcmp(proto->getEventIn(i)->getName(x3d), exposedName) == 0)
               isExposedField = true;
        }
        if (isExposedField) 
            continue;
        if (!(proto->getEventIn(i)->getFlags() && (FF_STATIC | FF_HIDDEN)))
            _interface.append(new InterfaceData(EL_EVENT_IN, i));
    }
}

