// 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 ("psend", "parallel_interface.oct");
// PKG_DEL: autoload ("psend", "parallel_interface.oct", "remove");

#include <octave/oct.h>
#include <octave/load-save.h>
#include <octave/ls-oct-binary.h>
#include <octave/oct-stream.h>

#include "parallel-gnutls.h"

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

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

DEFUN_DLD (psend, args, ,
           "-*- texinfo -*-\n\
@deftypefn {Loadable Function} {} psend (@var{value}, @var{connections})\n\
Send the value in variable @var{value} to all parallel cluster machines specified by @var{connections}.\n\
\n\
This function can be called both at the client machine and (with\n\
@code{reval}) at a server machine. See @code{pconnect} for a\n\
description of the @var{connections} variable, and @code{pserver} for\n\
a description of this variable (named @code{sockets}) at the server\n\
side. @var{connections} can contain all connections of the network, a\n\
subset of them, or a single connection. The machine at which\n\
@code{psend} was called (client or server), if contained in the\n\
@var{connections} variable, is ignored.\n\
\n\
The value sent with @code{psend} must be received with @code{precv} at\n\
the target machine. Note that values can be sent to each machine, even\n\
from a server machine to a different server machine.\n\
\n\
If @code{psend} is called at the client machine, a corresponding\n\
@code{precv} should have been called before at the target machine,\n\
otherwise the client will hang if @var{value} contains large data\n\
(which can not be held by the operating systems socket buffers).\n\
\n\
@seealso{pconnect, pserver, reval, precv, sclose, parallel_generate_srp_data, select_sockets}\n\
@end deftypefn")
{
  std::string fname ("psend");

  octave_value retval;

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

      return retval;
    }

  const octave_base_value &rep = args(1).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;
    }

  inthandler_dont_restart_syscalls __inthandler_guard__;

  // check each connection before a command is sent over any
  if (nconns < conns->get_all_connections ().numel ()) // it's a subnet
    for (int i = 0; i < nconns; i++)
      if (conns->get_connections ()(i)->is_pseudo_connection ())
        {
          error ("%s: using a subnet and own node was given as one of the receivers (index %i)",
                 fname.c_str (), i + 1);

          return retval;
        }
  if (! conns->is_server ())
    {
      bool command_errors = false, stream_errors = false;
      int err;
      for (int i = 0; i < nconns; i++)
        {
          if (conns->get_connections ()(i)->is_pseudo_connection ())
            continue;

          if ((err = conns->get_connections ()(i)->poll_for_errors ()))
            {
              if (err > 0)
                {
                  c_verror ("%s: a previous command at server with index %i caused an error",
                          fname.c_str (), i + 1);
                  command_errors = true;
                }
              else // err < 0
                {
                  c_verror ("%s: communication error with server with index %i",
                          fname.c_str (), i + 1);
                  stream_errors = true;
                }
            }
        }
      if (stream_errors)
        conns->close ();
      if (stream_errors || command_errors)
        {
          error ("error in psend");
          
          return retval;
        }
    }

  double sid;

  // args(0) is const, make copy
  octave_value val = args(0);

  for (int i = 0; i < nconns; i++)
    {
      if (conns->get_connections ()(i)->is_pseudo_connection ())
        continue;

      if (minimal_write_data (conns->get_connections ()(i)->
                              get_data_stream ()->get_ostream (), val)
          || ! conns->get_connections ()(i)->get_data_stream ()->good ())
        {
          conns->close ();

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

          return retval;
        }
    }

  return retval;
}
