// Copyright (C) 2002 Hayato Fujiwara <h_fujiwara@users.sourceforge.net>

// Copyright (C) 2010-2016 Olaf Till <i7tiol@t-online.de>

// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; If not, see <http://www.gnu.org/licenses/>.

// PKG_ADD: autoload ("precv", "parallel_interface.oct");
// PKG_DEL: autoload ("precv", "parallel_interface.oct", "remove");

#include <octave/oct.h>

#include <sys/socket.h>
#include <sys/poll.h>
#include <netinet/in.h>
#include <netdb.h>

#include "parallel-gnutls.h"

#if HAVE_UNISTD_H
#include <unistd.h>
#endif

DEFUN_DLD (precv, args, nargout,
           "-*- texinfo -*-\n\
@deftypefn {Loadable Function} {} precv (@var{single_connection})\n\
Receive a data value from the parallel cluster machine specified by @var{single_connection}.\n\
\n\
This function can be called both at the client machine and (with\n\
@code{reval}) at a server machine. @var{single_connection} must be a\n\
single connection obtained by indexing the @var{connections}\n\
variable. Please see @code{pconnect} for a description of the\n\
@var{connections} variable, and @code{pserver} for a description of\n\
this variable (named @code{sockets}) at the server side. If\n\
@var{single_connection} corresponds to the machine at which\n\
@code{precv} was called, an error is thrown.\n\
\n\
The value received with @code{precv} must be sent with @code{psend}\n\
from another machine of the cluster. Note that data can be transferred\n\
this way between each pair of machines, even sent by a server and\n\
received by a different server.\n\
\n\
If @code{precv} is called at the client machine, a corresponding\n\
@code{psend} should have been called before at the source machine,\n\
otherwise the client will hang.\n\
\n\
@seealso{pconnect, pserver, reval, psend, sclose, parallel_generate_srp_data, select_sockets}\n\
@end deftypefn")
{
  std::string fname ("precv");

  octave_value retval;

  if (args.length () != 1 ||
      args(0).type_id () != octave_parallel_connections::static_type_id ())
    {
      print_usage ();

      return retval;
    }

  const octave_base_value &rep = args(0).get_rep ();
  const octave_parallel_connections &cconns =
    dynamic_cast<const octave_parallel_connections&> (rep);
  octave_parallel_connections_rep *conns = cconns.get_rep ();
  int nconns = conns->get_connections ().numel ();

  if (conns->get_whole_network ()->is_closed ())
    {
      error ("%s: network is closed", fname.c_str ());

      return retval;
    }

  if (nconns == 0)
    return retval;

  if (nconns > 1)
    {
      error ("%s: data can only be read from a single connection",
             fname.c_str ());

      return retval;
    }

  octave_parallel_connection *conn = conns->get_connections ()(0);

  if (conn->is_pseudo_connection ())
    {
      error ("%s: the own node was specified to read data from",
             fname.c_str ());

      return retval;
    }

  inthandler_dont_restart_syscalls __inthandler_guard__;

  if (! conns->is_server ())
    {
      int err;
      if ((err = conn->wait_for_errors_or_data ()))
        {
          if (err > 0)
            error ("%s: a previous command at the server caused an error",
                   fname.c_str ());
          else // err < 0
            {
              conns->close ();

              error ("%s: communication error", fname.c_str ());
            }

          return retval;
        }
    }

  octave_value tc;

  if (conn->connection_read_data (tc) ||
      ! conn->get_data_stream ()->good ())
    {
      conns->close ();

      error ("%s: error in reading variable data\n", fname.c_str ());

      return retval;
    }

  if  (! tc.is_defined ())
    {
      conns->close ();

      error ("%s: error in reading variable\n", fname.c_str ());

      return retval;
    }


  return retval = tc;
}
