/****************************************************************************
 * 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 "./mdevices_setdevice.h"

#include "aqhome-cgi/modules/mdataclient.h"

#include <aqcgi/service/module.h>

#include <gwenhywfar/debug.h>
#include <gwenhywfar/timestamp.h>
#include <gwenhywfar/text.h>


/* ------------------------------------------------------------------------------------------------
 * defs and enums
 * ------------------------------------------------------------------------------------------------
 */

#define GBAS GWEN_Buffer_AppendString
#define GBAA GWEN_Buffer_AppendArgs



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

static void _handleDeviceForm(AQH_DATACLIENT *dc, AQH_DEVICE *device, GWEN_DB_NODE *dbPost, GWEN_BUFFER *dbuf);



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

void AQH_ModDevices_RunSetDevice(AQCGI_MODULE *m, AQCGI_REQUEST *rq, AQCGI_SESSION *session, AQH_DATACLIENT *dc, GWEN_BUFFER *dbuf)
{
  AQCGI_SERVICE *sv;
  GWEN_DB_NODE *dbPost;
  const char *sDeviceName;
  AQH_DEVICE *device;

  DBG_ERROR(NULL, "Post device.html");
  /* sample data */
  sv=AQH_ModService_GetService(m);
  dbPost=AQCGI_Request_GetDbPostBody(rq);
  sDeviceName=dbPost?GWEN_DB_GetCharValue(dbPost, "device", 0, NULL):NULL;
  DBG_ERROR(NULL, "Device=[%s]", sDeviceName?sDeviceName:"");

  device=AQH_ModDevices_GetDevice(dc, sDeviceName);
  if (device) {
    int rv;

    DBG_ERROR(NULL, "Reading data from form");
    _handleDeviceForm(dc, device, dbPost, dbuf);
    DBG_ERROR(NULL, "Updating device on server");
    rv=AQH_DataClient_ModDevice(dc, device);
    if (rv<0) {
      DBG_ERROR(NULL, "here (%d)", rv);
    }
    AQH_Device_free(device);
  }
  else {
    DBG_ERROR(NULL, "device not found");
  }

  AQH_ModDevices_RedirectToDevice(rq, "device.html", device);
}



void _handleDeviceForm(AQH_DATACLIENT *dc, AQH_DEVICE *device, GWEN_DB_NODE *dbPost, GWEN_BUFFER *dbuf)
{
  AQH_Device_SetRoomName(device, GWEN_DB_GetCharValue(dbPost, "roomName", 0, NULL));
  AQH_Device_SetNameForGui(device, GWEN_DB_GetCharValue(dbPost, "nameForGui", 0, NULL));
  AQH_Device_SetLocation(device, GWEN_DB_GetCharValue(dbPost, "location", 0, NULL));
  AQH_Device_SetDescription(device, GWEN_DB_GetCharValue(dbPost, "description", 0, NULL));
}





