/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2023 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 "./loop_tty.h"
#include "./loop_tty_ipc.h"
#include "./loop_tty_broker.h"
#include "./aqhomed_p.h"
#include "./tty_log.h"
#include "./db.h"

#include "aqhome/msg/endpoint_tty.h"
#include "aqhome/msg/msg_node.h"
#include "aqhome/msg/msg_value2.h"
#include "aqhome/ipc/endpoint_ipc.h"
#include "aqhome/ipc/nodes/msg_ipc_forward.h"
#include "aqhome/ipc/nodes/msg_ipc_value.h"

#include <gwenhywfar/gwenhywfar.h>
#include <gwenhywfar/args.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/endpoint_tcpd.h>



/* ------------------------------------------------------------------------------------------------
 * defines
 * ------------------------------------------------------------------------------------------------
 */

#define I18N(msg) msg
#define I18S(msg) msg



/* ------------------------------------------------------------------------------------------------
 * forward declarations
 * ------------------------------------------------------------------------------------------------
 */

static void _handleTtyMsg(AQHOMED *aqh, const GWEN_MSG *msg);



/* ------------------------------------------------------------------------------------------------
 * implementations
 * ------------------------------------------------------------------------------------------------
 */


void AqHomed_ReadAndHandleTtyMessages(AQHOMED *aqh)
{
  GWEN_MSG *msg;

  while( (msg=GWEN_MsgEndpoint_TakeFirstReceivedMessage(aqh->ttyEndpoint)) ) {
    _handleTtyMsg(aqh, msg);
    GWEN_Msg_free(msg);
  }
}



void _handleTtyMsg(AQHOMED *aqh, const GWEN_MSG *msg)
{
  if (aqh->logFile)
    AqHomed_LogTtyMsg(aqh, msg);
  if (aqh->nodeDb)
    AqHomed_NodeMsgToDb(aqh, msg);
  if (aqh->ipcdEndpoint)
    AqHomed_ForwardTtyMsgToIpcClients(aqh, msg);
  if (aqh->brokerEndpoint)
    AqHomed_ForwardTtyMsgToBroker(aqh, msg);
}



