/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2025 Martin Preuss, all rights reserved.
 *
 * The license for this file can be found in the file COPYING which you
 * should have received along with this file.
 ****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "./tty_endpoint.h"

#include <aqhome/ipc2/node_msgreader.h>
#include <aqhome/ipc2/msgwriter.h>
#include <aqhome/ipc2/tty_object.h>
#include <aqhome/ipc2/endpoint.h>
#include <aqhome/events2/fdobject.h>

#include <gwenhywfar/debug.h>

#include <unistd.h>



/* ------------------------------------------------------------------------------------------------
 * code
 * ------------------------------------------------------------------------------------------------
 */

AQH_OBJECT *AQH_TtyEndpoint2_new(AQH_EVENT_LOOP *eventLoop, int fd, int noAttn)
{
  int fdCopy;
  AQH_OBJECT *fdReader;
  AQH_OBJECT *fdWriter;
  AQH_OBJECT *msgReader;
  AQH_OBJECT *msgWriter;
  AQH_OBJECT *endpoint;

  fdCopy=dup(fd);

  fdReader=AQH_TtyObject_new(eventLoop, fd, AQH_FDOBJECT_FDMODE_READ);
  AQH_FdObject_FlushInput(fdReader);
  msgReader=AQH_NodeMsgReader_new(eventLoop, fdReader);
  AQH_Object_Enable(msgReader);

  fdWriter=AQH_TtyObject_new(eventLoop, fdCopy, AQH_FDOBJECT_FDMODE_WRITE);
  if (noAttn) {
    DBG_ERROR(NULL, "Adding noAttn flag");
    AQH_Object_AddFlags(fdWriter, AQH_TTYOBJECT_FLAGS_NOATTN);
  }
  msgWriter=AQH_MsgWriter_new(eventLoop, fdWriter);

  endpoint=AQH_Endpoint_new(eventLoop, msgReader, msgWriter);
  return endpoint;
}




