/****************************************************************************
 * 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 "./aqhome_data_p.h"
#include "aqhome/ipc/endpoint_ipc.h"

#include <gwenhywfar/misc.h>
#include <gwenhywfar/debug.h>





AQHOME_DATA *AqHomeData_new()
{
  AQHOME_DATA *aqh;

  GWEN_NEW_OBJECT(AQHOME_DATA, aqh);
  aqh->storageMutex=GWEN_Mutex_new();

  return aqh;
}



void AqHomeData_free(AQHOME_DATA *aqh)
{
  if (aqh) {
    GWEN_Mutex_free(aqh->storageMutex);

    GWEN_MsgEndpoint_free(aqh->ipcdEndpoint);
    GWEN_DB_Group_free(aqh->dbArgs);
    AQH_Storage_free(aqh->storage);
    free(aqh->pidFile);

    GWEN_FREE_OBJECT(aqh);
  }
}



GWEN_MSG_ENDPOINT *AqHomeData_GetIpcdEndpoint(const AQHOME_DATA *aqh)
{
  return aqh?(aqh->ipcdEndpoint):NULL;
}



GWEN_DB_NODE *AqHomeData_GetDbArgs(const AQHOME_DATA *aqh)
{
  return aqh?(aqh->dbArgs):NULL;
}



AQH_STORAGE *AqHomeData_GetStorage(const AQHOME_DATA *aqh)
{
  return aqh?(aqh->storage):NULL;
}



const char *AqHomeData_GetPidFile(const AQHOME_DATA *aqh)
{
  return aqh?aqh->pidFile:NULL;
}



int AqHomeData_GetTimeout(const AQHOME_DATA *aqh)
{
  return aqh?aqh->timeout:0;
}



int AqHomeData_LockStorage(AQHOME_DATA *aqh)
{
  int rv;

  rv=GWEN_Mutex_Lock(aqh->storageMutex);
  if (rv<0) {
    DBG_ERROR(AQH_LOGDOMAIN, "Error obtaining lock on storage mutex");
    return rv;
  }
  return rv;
}



int AqHomeData_UnlockStorage(AQHOME_DATA *aqh)
{
  int rv;

  rv=GWEN_Mutex_Unlock(aqh->storageMutex);
  if (rv<0) {
    DBG_ERROR(AQH_LOGDOMAIN, "Error releasing lock on storage mutex");
    return rv;
  }
  return rv;
}



GWEN_MSG_ENDPOINT *AqHomeData_GetIpcEndpointByServiceName(const AQHOME_DATA *aqh, const char *serviceName)
{
  GWEN_MSG_ENDPOINT *ep;

  ep=GWEN_MsgEndpoint_Tree2_GetFirstChild(aqh->ipcdEndpoint);
  while(ep) {
    const char *s;

    s=AQH_IpcEndpoint_GetServiceName(ep);
    if (s && *s && strcasecmp(s, serviceName)==0)
      return ep;
    ep=GWEN_MsgEndpoint_Tree2_GetNext(ep);
  }

  return NULL;
}





