/*
  TCP/IP の相互接続を実現するクラス
  Satofumi KAMIMURA
  $Id: peerConnection.cpp 286 2008-10-20 09:40:22Z satofumi $
*/

#include "peerConnection.h"
#include "tcpipServer.h"


PeerConnection::PeerConnection(void)
  : con(NULL), error_message("Connection device is not specified") {
}


PeerConnection::~PeerConnection(void) {
  delete con;
}


const char* PeerConnection::what(void) {
  return error_message.c_str();
}


bool PeerConnection::isConnected(void) {
  return (con) ? con->isConnected() : false;
}


int PeerConnection::connect(const char* host, long port, long timeout) {

  // 相手側に接続を行う
  int ret_value = raw_connect(host, port);
  error_message = con->what();
  if (ret_value >= 0) {
    return ret_value;
  }
  delete con;

  // 接続用ポートを立てる
  TcpipServer server_con;
  server_con.activate(port);
  con = server_con.accept(timeout);
  if (con) {
    error_message = con->what();
    return 0;
  }
  error_message = "connection timeout";
  return -1;
}


void PeerConnection::raw_disconnect(void) {
  delete con;
  con = NULL;
  error_message = "disconnected";
}


int PeerConnection::raw_connect(const char* device, long baudrate) {
  con = new TcpipDevice();
  int ret_value = con->connect(device, baudrate);
  error_message = con->what();

  return ret_value;
}


void PeerConnection::raw_check(int size, long timeout) {
}


int PeerConnection::raw_send(const char* data, int len) {
  if (!con) {
    return ConnectionDevice::NotConnected;
  }
  return con->send(data, len);
}


int PeerConnection::recv(char* data, int maxlen, long timeout) {
  if (!con) {
    return ConnectionDevice::NotConnected;
  }
  return con->recv(data, maxlen, timeout);
}
