/*****************************
File:       RemoteSF.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/RemoteSF.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 S>
RemoteSF<S>::RemoteSF(X3DType t, 
                      Inst<SFSender> _toBeSent,
                      Inst< BufferedSField<S> > _received) :
received   (_received),
toBeSent (_toBeSent) {
   
   type_name = "RemoteSF";
   database.initFields( this );

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

// ----------------------------------------------------------------------------
template <class S>
RemoteSF<S>::~RemoteSF() {
   // 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 S>
H3DNodeDatabase RemoteSF<S>::database(   
   "RemoteSF<S>", 
   NULL,
   typeid(RemoteSF<S>),
   &RemoteField::database);

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

// ----------------------------------------------------------------------------
template <class S>
void RemoteSF<S>::initialize() {
  RemoteField::initialize();

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

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

// ----------------------------------------------------------------------------
template <class S>
void RemoteSF<S>::SFSender::update() {
   RemoteSF<S> * fld_senderP = static_cast<RemoteSF<S> *>(getOwner());
   S * fld = static_cast<S *>(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 S>
void RemoteSF<S>::SFSender::setValue( const typename S::value_type & val, int id ) {
   RemoteSF<S> * fld_senderP = static_cast<RemoteSF<S> *>(getOwner());
   S::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();
   }
}

