/*****************************
File:       RemoteClient.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/RemoteClient.h"
#include "H3DNetworkingUtils/sockwrap.h"
#include "H3DNetworkingUtils/fail.h"
#include "H3DNetworkingUtils/RemoteSync.h"

using namespace H3D;
using namespace H3DNetworkingUtils;

H3DNodeDatabase RemoteClient::database(   
  "RemoteClient", 
  NULL,
  typeid(RemoteClient),
  &RemoteConnection::database);

namespace RemoteClientInternals {   
  FIELDDB_ELEMENT( RemoteClient, remoteHost, INPUT_OUTPUT );
  FIELDDB_ELEMENT( RemoteClient, remotePort, INPUT_OUTPUT );
  FIELDDB_ELEMENT( RemoteClient, open, INPUT_OUTPUT );
  FIELDDB_ELEMENT( RemoteClient, autoReconnect, INPUT_OUTPUT );
}


// ----------------------------------------------------------------------------
RemoteClient::RemoteClient(string _socket_type,
                           Inst<SFString     > _remoteHost,
                           Inst<SFInt32      > _remotePort,
                           Inst<OpenHandler  > _open,
                           Inst<SFBool       > _autoReconnect) :
socket_type (_socket_type),
remoteHost       (_remoteHost),
remotePort       (_remotePort),
open              (_open),
restart_requested (false),
autoReconnect    (_autoReconnect),
opened_once       (false),
start_called (false),
last_connect_attempt_time (0) {

  type_name = "RemoteClient";
  database.initFields( this );

  open->setOwner(this);
  open->setValue(false);
  remoteHost->setValue("localhost");
  remotePort->setValue(9876);
  autoReconnect->setValue(true);
}

// ----------------------------------------------------------------------------
void RemoteClient::initialize() {
  RemoteConnection::initialize();
  if (open->getValue())  {
    startClient(remoteHost->getValue(), remotePort->getValue());
  }
  if (remoteSync->getValue()) {
    open->route( remoteSync->getValue()->timer->enabled );
  }
}

// ----------------------------------------------------------------------------
void RemoteClient::startClient(string host, int port_number) {
  // Called in graphics thread.

  if (start_called ) {
    return;
  }
  start_called = true;

  sprintf(addr, "%s:%d", host.data(), port_number);
  remote_end.scan(addr);

  if (autoReconnect->getValue()) {
      restart_requested = true;
  }
  restartClient();
  opened_once = true;
}

// ----------------------------------------------------------------------------
void RemoteClient::close(  ) {
  RemoteConnection::close();
  if (autoReconnect->getValue()) {
    restart_requested = true;
  }
}

// ----------------------------------------------------------------------------
void RemoteClient::OpenHandler::update(  ) {
  RemoteClient * clientP = static_cast<RemoteClient*>(getOwner());
  SFBool * val = static_cast<SFBool*>(event.ptr);
  if (val->getValue() != value) {
     if (clientP->initialized) {
        if (val->getValue()) {
           if (clientP->openedBefore()) {
              clientP->requestRestart();
           } else {
              clientP->startClient(clientP->remoteHost->getValue(),
                                 clientP->remotePort->getValue());
           }
        } else {
           clientP->requestClose();
        }
     }
     value = val->getValue();
  }
}

// ----------------------------------------------------------------------------
void RemoteClient::OpenHandler::setValue( bool const & val, int id ) {
  RemoteClient * clientP = static_cast<RemoteClient*>(getOwner());
  if (val != value) {
     if (clientP->initialized) {
        if (val) {
           if (clientP->openedBefore()) {
              clientP->requestRestart();
           } else {
              clientP->startClient(clientP->remoteHost->getValue(),
              clientP->remotePort->getValue());
           }
        } else {
           clientP->requestClose();
        }
     }
     value = val;
  }
}

// ----------------------------------------------------------------------------
bool RemoteClient::doClosedActions() {
  // Called in graphics thread

  // This gets called repeatedly while connection is closed.
  if (restart_requested && !is_connected.get()) {
     H3DTime now = TimeStamp::now();
     if ((now - last_connect_attempt_time) > 3.0) {
        string msg("Trying to connect to ");
        msg += socket_type;
        msg += " server\n";
        showInfo(msg);
        restartClient();
        last_connect_attempt_time = now;
     }
  }
  return false;
}
