/****************************************************************************
 * 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 "./u_rooms.h"
#include "./u_objects.h"
#include "./aqhomehttp.h"

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



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



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

static int _addOrEditObject(AQH_HTTP_URLHANDLER *uh, GWEN_DB_NODE *db, int id);
static GWEN_DB_NODE *_findObjectByIdAndReturnAsDb(AQH_HTTP_URLHANDLER *uh, int id);
static int _writeAddPage(AQH_HTTP_URLHANDLER *uh, AQH_HTTP_REQUEST *rq, GWEN_DB_NODE *dbValues, GWEN_BUFFER *pageBuf);
static int _writeEditPage(AQH_HTTP_URLHANDLER *uh, AQH_HTTP_REQUEST *rq, GWEN_DB_NODE *dbValues, GWEN_BUFFER *pageBuf);
static void _listObjectsIntoBuffer(AQH_HTTP_URLHANDLER *uh, GWEN_BUFFER *pageBuf);

static void _writeEditingTable(AQH_HTTP_URLHANDLER *uh, GWEN_DB_NODE *dbValues, GWEN_BUFFER *pageBuf);
static void _setFromObject(AQH_ROOM *r, const AQH_ROOM *srcRoom);



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

AQH_HTTP_URLHANDLER *AQH_RoomsHttpUrlHandler_new(AQH_SERVICE *sv)
{
  AQH_HTTP_URLHANDLER *uh;

  uh=AQH_ObjectsHttpUrlHandler_new(sv,
                                   AQHOME_HTTP_PERMS_LIST_ROOMS,
                                   AQHOME_HTTP_PERMS_ADD_ROOM,
                                   AQHOME_HTTP_PERMS_DEL_ROOM,
                                   AQHOME_HTTP_PERMS_EDIT_ROOM,
                                   "/rooms/list");
  AQH_ObjectsHttpUrlHandler_SetAddOrEditObjectFn(uh, _addOrEditObject);
  AQH_ObjectsHttpUrlHandler_SetFindObjectByIdAndReturnAsDbFn(uh, _findObjectByIdAndReturnAsDb);
  AQH_ObjectsHttpUrlHandler_SetWriteAddPageFn(uh, _writeAddPage);
  AQH_ObjectsHttpUrlHandler_SetWriteEditPageFn(uh, _writeEditPage);
  AQH_ObjectsHttpUrlHandler_SetListObjectsIntoBufferFn(uh, _listObjectsIntoBuffer);

  return uh;
}



int _addOrEditObject(AQH_HTTP_URLHANDLER *uh, GWEN_DB_NODE *db, int id)
{
  AQH_SERVICE *sv;
  AQH_STORAGE *sto;
  AQH_ROOM *newRoom;
  const char *roomName;
  int rv;

  sv=AQH_HttpUrlHandler_GetHttpService(uh);
  sto=AqHomeHttpService_GetStorage(sv);

  newRoom=AQH_Room_fromDb(db);

  roomName=AQH_Room_GetName(newRoom);
  if (!(roomName && *roomName)) {
    DBG_INFO(NULL, "Missing room name");
    AQH_Room_free(newRoom);
    return GWEN_ERROR_INVALID;
  }

  rv=AqHomeHttpService_LockStorage(sv);
  if (rv<0) {
    DBG_ERROR(NULL, "Error locking storage");
    AQH_Room_free(newRoom);
    return GWEN_ERROR_IO;
  }

  if (id>0) {
    AQH_ROOM *r;

    DBG_INFO(NULL, "Edit existing room");
    r=AQH_Storage_GetRoomById(sto, id);
    if (r==NULL) {
      AqHomeHttpService_UnlockStorage(sv);
      DBG_ERROR(NULL, "Room %d not found", id);
      AQH_Room_free(newRoom);
      return GWEN_ERROR_NOT_FOUND;
    }
    AQH_Room_SetId(r, id);
    _setFromObject(r, newRoom);
    AQH_Storage_AddRuntimeFlags(sto, AQH_STORAGE_RTFLAGS_MODIFIED);
  }
  else {
    AQH_ROOM *r;

    DBG_INFO(NULL, "Adding new room");
    r=AQH_Storage_GetRoomByName(sto, roomName);
    if (r) {
      AqHomeHttpService_UnlockStorage(sv);
      DBG_ERROR(NULL, "Room %s exists", roomName);
      AQH_Room_free(newRoom);
      return GWEN_ERROR_FOUND;
    }
    r=AQH_Room_new();
    AQH_Room_SetId(r, 0);
    _setFromObject(r, newRoom);
    AQH_Storage_AddRoom(sto, r);
    AQH_Storage_AddRuntimeFlags(sto, AQH_STORAGE_RTFLAGS_MODIFIED);
  }
  AQH_Room_free(newRoom);

  rv=AqHomeHttpService_UnlockStorage(sv);
  if (rv<0) {
    DBG_ERROR(NULL, "Error unlocking storage");
    return GWEN_ERROR_IO;
  }
  return 0;
}



void _setFromObject(AQH_ROOM *r, const AQH_ROOM *srcRoom)
{
  AQH_Room_SetName(r, AQH_Room_GetName(srcRoom));
  AQH_Room_SetDescription(r, AQH_Room_GetDescription(srcRoom));
}



GWEN_DB_NODE *_findObjectByIdAndReturnAsDb(AQH_HTTP_URLHANDLER *uh, int id)
{
  AQH_SERVICE *sv;
  AQH_STORAGE *sto;
  const AQH_ROOM *r;

  sv=AQH_HttpUrlHandler_GetHttpService(uh);
  sto=AqHomeHttpService_GetStorage(sv);
  
  r=AQH_Storage_GetRoomById(sto, id);
  if (r) {
    GWEN_DB_NODE *db;
  
    db=GWEN_DB_Group_new("room");
    AQH_Room_toDb(r, db);
    return db;
  }
  return NULL;
}



int _writeAddPage(AQH_HTTP_URLHANDLER *uh, AQH_HTTP_REQUEST *rq, GWEN_DB_NODE *dbValues, GWEN_BUFFER *pageBuf)
{
  GWEN_Buffer_AppendArgs(pageBuf,
                         "<h2>%s</h2><br>\n"
			 "<form action=\"/rooms/add\" method=\"post\" enctype=\"application/x-www-form-urlencoded\">",
			 I18N("Add Room"));
  _writeEditingTable(uh, dbValues, pageBuf);
  GWEN_Buffer_AppendArgs(pageBuf, "<input type=\"submit\" value=\"%s\"></form>", I18N("Submit"));
  return 0;
}



int _writeEditPage(AQH_HTTP_URLHANDLER *uh, AQH_HTTP_REQUEST *rq, GWEN_DB_NODE *dbValues, GWEN_BUFFER *pageBuf)
{

  GWEN_Buffer_AppendArgs(pageBuf,
                         "<h2>%s</h2><br>\n"
			 "<form action=\"/rooms/edit/%lu\" method=\"post\" enctype=\"application/x-www-form-urlencoded\">",
			 I18N("Edit Room"),
			 (long unsigned int)(dbValues?GWEN_DB_GetIntValue(dbValues, "id", 0, 0):0));
  _writeEditingTable(uh, dbValues, pageBuf);
  GWEN_Buffer_AppendArgs(pageBuf, "<input type=\"submit\" value=\"%s\"></form>", I18N("Submit"));
  return 0;
}



void _writeEditingTable(AQH_HTTP_URLHANDLER *uh, GWEN_DB_NODE *dbValues, GWEN_BUFFER *pageBuf)
{
  GWEN_Buffer_AppendArgs(pageBuf,
			 "  <table>"
			 "    <tr>"
			 "      <td><label for=\"name\">%s: </label></td>"
			 "      <td><input type=\"text\" name=\"name\" value=\"%s\" required></td>"
			 "    </tr>"
			 "    <tr>"
			 "      <td><label for=\"description\">%s: </label></td>"
			 "      <td><input type=\"text\" name=\"description\" value=\"%s\" ></td>"
			 "    </tr>"
			 "  </table>",
			 I18N("Name"),
			 dbValues?GWEN_DB_GetCharValue(dbValues, "name", 0, ""):"",
			 I18N("Description"),
			 dbValues?GWEN_DB_GetCharValue(dbValues, "description", 0, ""):"");
}



void _listObjectsIntoBuffer(AQH_HTTP_URLHANDLER *uh, GWEN_BUFFER *pageBuf)
{
  AQH_SERVICE *sv;
  AQH_STORAGE *sto;
  const AQH_ROOM_LIST *rl;

  sv=AQH_HttpUrlHandler_GetHttpService(uh);
  sto=AqHomeHttpService_GetStorage(sv);

  GWEN_Buffer_AppendArgs(pageBuf,
			 "<h2>%s</h2>"
			 "<table class=\"dataTable\">"
			 "<thead>"
			 "  <tr><th>%s</th><th>%s</th><th></th></tr>"
			 "</thead>",
			 I18N("Rooms"),
			 I18N("Name"),
			 I18N("Description"));
  GWEN_Buffer_AppendString(pageBuf, "<tbody>");
  rl=AQH_Storage_GetRoomList(sto);
  if (rl) {
    const AQH_ROOM *r;

    r=AQH_Room_List_First(rl);
    while(r) {
      long unsigned int id;
      const char *name;
      const char *descr;

      id=(long unsigned int) AQH_Room_GetId(r);
      name=AQH_Room_GetName(r);
      descr=AQH_Room_GetDescription(r);

      GWEN_Buffer_AppendArgs(pageBuf,
			     "<tr><td>%s</td><td>%s</td>"
			     "<td><a href=\"/rooms/edit/%lu\">"
			     "<IMG src=\"/pics/edit.png\" width=32 height=32 align=left border=0></a></td>"
			     "</tr>",
			     name?name:"", descr?descr:"", id);
      r=AQH_Room_List_Next(r);
    }
  }
  GWEN_Buffer_AppendString(pageBuf, "</tbody>");
  GWEN_Buffer_AppendArgs(pageBuf, "</table><a href=\"/rooms/add\">%s</a><br>", I18N("Add Room"));
}





