/*****************************
File:       RemoteMF.CPP
Language:   C++ (header)
Project:    H3DNetworkingUtils
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.

The Original Code is H3DNetworkingUtils v1.0.

The Initial Developer of the Original Code is CSIRO.
Portions created by the Initial Developer are Copyright (C) 1009 CSIRO. All Rights Reserved.
Contributor(s):
    Chris Gunn  <Chris.Gunn@csiro.au> <ChrisJGunn@gmail.com>
***************************/
#include "H3DNetworkingUtils/RemoteMF.h"
#include <stdio.h>
#include "H3DNetworkingUtils/fail.h"
#include "H3DNetworkingUtils/threadwrap.h"
#include "H3DNetworkingUtils/systypes.h"

#include <iomanip>
#include <string>
#include <stdlib.h>

using namespace H3D;
using namespace H3D::X3DTypes;
using namespace H3DNetworkingUtils;

// ----------------------------------------------------------------------------
template <class M>
RemoteMF<M>::RemoteMF(X3DType t, 
                      Inst<MFSender> _toBeSent,
                      Inst< BufferedMField<M> > _received) :
received   (_received),
toBeSent (_toBeSent) {
   
   type_name = "RemoteMF";
   database.initFields( this );

   toBeSent->setX3DType(t);
   received->setX3DType(t);
   toBeSent->setOwner(this);
   received->setOwner(this);
}

// ----------------------------------------------------------------------------
template <class M>
RemoteMF<M>::~RemoteMF() {
   // If we are a haptic field, there is a dummy force effect running in the haptics loop.
   // We need to wait for the last one to finish before destroying ourselves because it refers to 
   // data in this class which will be destroyed.
   if (isHapticField->getValue()) {
      Sleep(40);
   }
}

// ----------------------------------------------------------------------------
template <class M>
H3DNodeDatabase RemoteMF<M>::database(   
   "RemoteMF<M>", 
   NULL,
   typeid(RemoteMF<M>),
   &RemoteField::database);

///Can't do this as we can't put in the 'typename M::value_type'
///namespace RemoteSFInternals {
///  FIELDDB_ELEMENT( RemoteMF<typename M::value_type>, toBeSent, INPUT_ONLY );
///  FIELDDB_ELEMENT( RemoteMF<typename M::value_type>, received, OUTPUT_ONLY );
///}

// ----------------------------------------------------------------------------
template <class M>
void RemoteMF<M>::initialize() {
   RemoteField::initialize();

   if (bufferStrategy->getValue() == "NONE") {
      received->setBufferStrategy(BufferedMField<M>::NONE);
   } else if (bufferStrategy->getValue() == "SET_ONE_PER_CYCLE") {
      received->setBufferStrategy(BufferedMField<M>::SET_ONE_PER_CYCLE);
   } else if (bufferStrategy->getValue() == "SET_ALL") {
      received->setBufferStrategy(BufferedMField<M>::SET_ALL);
   }
}

// ----------------------------------------------------------------------------
template <class M>
void RemoteMF<M>::writeField () {
  if (conP->isConnected->getValue()) {
    conP->writeFieldHeader(fieldId->getValue(), timestamps->getValue());
    writeValue(toBeSent->getValue(id));
  }
}

// ----------------------------------------------------------------------------
template <class M>
void RemoteMF<M>::MFSender::update(  ) {
   RemoteMF<M> * fld_senderP = static_cast<RemoteMF<M> *>(getOwner());
   M * fld = static_cast<M *>(event.ptr);
   if (fld) {
      value = fld->getValue();
      // If we are doing periodic sending, we don't send as soon as the
      // field changes.
      if (send_on_change && fld_senderP->isConnected()) {
         // Make sure we are not just reflecting back a value that we just received.
         if (event.time_stamp > fld_senderP->received->getLatestEvent().time_stamp) {
            fld_senderP->lockWriteThread();
            fld_senderP->writeField();
            fld_senderP->sendPacket();
            fld_senderP->unlockWriteThread();
         }
      }
   }
}

// ----------------------------------------------------------------------------
template <class M>
void RemoteMF<M>::MFSender::setValue( const std::vector<typename M::value_type> & val, int id) {
   RemoteMF<M> * fld_senderP = static_cast<RemoteMF<M> *>(getOwner());
   M::setValue(val, id);
   // If we are doing periodic sending, we don't send as soon as the
   // field changes.
   if (send_on_change && fld_senderP->isConnected()) {
      fld_senderP->lockWriteThread();
      fld_senderP->writeField();
      fld_senderP->sendPacket();
      fld_senderP->unlockWriteThread();
   }
}




