<?php

require_once 'Encoding.php';

use \ForceUTF8\Encoding;

class eoServerRequest{
  var $_xml;
  var $_host;
  var $_port;
  var $_eoc;
  var $_socket;

  function __construct($host,$port,$eoc,&$xml){
    $this->_xml = $xml;
    $this->_host = $host;
    $this->_port = $port;
    $this->_eoc = $eoc;
    $this->_socket = false;
  }

  function connect()
  {
    /* Create a TCP/IP socket. */
    $this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($this->_socket === false) {
      $this->_xml->addChild('status','0');
      $this->_xml->addChild('message',socket_strerror(socket_last_error()));
      return false;
    }

    $result = socket_connect($this->_socket, $this->_host, $this->_port);
    if ($result === false) {
      $this->_xml->addChild('status','0');
      $this->_xml->addChild('message','Failed to connect to server');
      error_log('Failed to connect to server : '.$this->_host.':'.$this->_port);
      socket_close($this->_socket);
      return false;
    }
    return true;
  }

  function disconnect()
  {
    socket_close($this->_socket);
  }

  function send(&$in)
  {
    $msg =  Encoding::toUTF8($in);
    socket_write($this->_socket, $msg, strlen($msg));
    socket_write($this->_socket, $this->_eoc, strlen($this->_eoc));
  }

  function receive()
  {
    $ret = 0;
    $length = 0;
    $bfr = '';
    $out = '';
    while ($ret = socket_recv($this->_socket, $bfr, 1024, 0)){

       $out.= $bfr;
       $length += $ret;
       if(ord($bfr[$ret-1]) === $this->_eoc){
        break;
       }
    }
    if($out != ''){
      $out = substr($out,0,$length-1);


      $a = explode('|', $out);

      for($i = 0 ; $i < count($a); $i++)
      {

        $elem = explode('=', $a[$i],2);

        $this->_xml->addChild($elem[0],$elem[1]);

      }
    }else{
      $this->_xml->addChild('status','0');
      $this->_xml->addChild('message','No answer received');
    }
  }
}

?>
