/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2026 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 "./nodes/ping.h"
#include "./nodes/flash.h"
#include "./nodes/settime.h"
#include "./nodes/getnodes.h"
#include "./data/getvalues.h"
#include "./data/getdevices.h"
#include "./data/adddata.h"
#include "./data/getdatapoints.h"
#include "./data/getfirstdata.h"
#include "./data/getlastdata.h"
#include "./data/getperioddata.h"
#include "./data/setdata.h"
#include "./data/moddevice.h"
#include "./data/watch.h"
#include "./data/devicestate.h"
#include "./data/imgperioddata.h"
#include "./image/readbmp.h"

#include <aqhome/api.h>
#include <aqhome/aqhome.h>

#include <gwenhywfar/gwenhywfar.h>
#include <gwenhywfar/db.h>
#include <gwenhywfar/args.h>
#include <gwenhywfar/logger.h>
#include <gwenhywfar/debug.h>
#include <gwenhywfar/cgui.h>
#include <gwenhywfar/funcs.h>
#include <gwenhywfar/i18n.h>


#define I18S(msg) msg
#define I18N(msg) GWEN_I18N_Translate(PACKAGE, msg)





int main(int argc, char **argv)
{
  GWEN_DB_NODE *dbArgs;
  int rv;
  GWEN_GUI *gui;
  const char *s;
  const char *cmd;
  const GWEN_ARGS args[]= {
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "loglevel",                   /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "L",                          /* short option */
      "loglevel",                   /* long option */
      I18S("Specify loglevel"),     /* short description */
      I18S("Specify loglevel")      /* long description */
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "charset",                    /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      0,                            /* short option */
      "charset",                    /* long option */
      I18S("Specify the output character set"),       /* short description */
      I18S("Specify the output character set")        /* long description */
    },
    {
      GWEN_ARGS_FLAGS_HELP | GWEN_ARGS_FLAGS_LAST, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "help",                       /* name */
      0,                            /* minnum */
      0,                            /* maxnum */
      "h",                          /* short option */
      "help",
      I18S("Show this help screen."),
      I18S("Show this help screen.")
    }
  };
  const GWEN_FUNCS cmdDefArray[]= {
    GWEN_FE_DAH("ping", AQH_Tool_Ping, I18N("Ping a given node on the network")),
    GWEN_FE_DAH("time", AQH_Tool_SetTime, I18N("Set node network time (handled by RTC module)")),
    GWEN_FE_DAH("flash", AQH_Tool_Flash, I18N("Flash a given node on the network")),
    GWEN_FE_DAH("getnodes", AQH_Tool_GetNodes, I18N("Request list of known devices on the network")),
    GWEN_FE_DAH("getvalues", AQH_Tool_GetValues, I18N("Request list of known values on the data server")),
    GWEN_FE_DAH("getdevices", AQH_Tool_GetDevices, I18N("Request list of known devices on the data server")),
    GWEN_FE_DAH("adddata", AQH_Tool_AddDataPoint, I18N("Send a datapoint to the data server")),
    GWEN_FE_DAH("addjsondata", AQH_Tool_AddDataPoint, I18N("(same as adddata)")),
    GWEN_FE_DAH("getdata", AQH_Tool_GetDataPoints, I18N("Request list of datapoints for a value on the data server")),
    GWEN_FE_DAH("getfirstdata", AQH_Tool_GetFirstData, I18N("Request first datapoints for a value on the data server")),
    GWEN_FE_DAH("getlastdata", AQH_Tool_GetLastData, I18N("Request last datapoints for a value on the data server")),
    GWEN_FE_DAH("getperioddata", AQH_Tool_GetPeriodData, I18N("Request datapoints from a date range for a value on the data server")),
    GWEN_FE_DAH("setdata", AQH_Tool_SetData, I18N("Set data for a value on the data server (e.g. a switch or thermostat)")),
    GWEN_FE_DAH("moddevice", AQH_Tool_ModDevice, I18N("Modify a device on the data server")),
    GWEN_FE_DAH("watch", AQH_Tool_Watch, I18N("Watch and print changes of values on the data server")),
    GWEN_FE_DAH("devicestate", AQH_Tool_DeviceState, I18N("Show state of devices")),
    GWEN_FE_DAH("imgperioddata", AQH_Tool_ImgPeriodData, I18N("Create diagram of datapoints from a date range")),
    GWEN_FE_DAH("dumpbmp", AQH_Tool_DumpBmpFile, I18N("Dump headers of BMP file")),
    GWEN_FE_END(),
  };
  const GWEN_FUNCS *func;

  rv=GWEN_Init();
  if (rv) {
    fprintf(stderr, "ERROR: Unable to init Gwen.\n");
    return 2;
  }

  gui=GWEN_Gui_CGui_new();
  GWEN_Gui_SetGui(gui);


  GWEN_Logger_Open(0, "aqhome-tool", 0, GWEN_LoggerType_Console, GWEN_LoggerFacility_User);
  GWEN_Logger_SetLevel(NULL, GWEN_LoggerLevel_Notice);

  rv=AQH_Init();
  if (rv<0) {
    DBG_INFO(NULL, "here (%d)", rv);
    return 2;
  }

  dbArgs=GWEN_DB_Group_new("arguments");
  rv=GWEN_Args_Check(argc, argv, 1, GWEN_ARGS_MODE_ALLOW_FREEPARAM | GWEN_ARGS_MODE_STOP_AT_FREEPARAM, args, dbArgs);
  if (rv==GWEN_ARGS_RESULT_ERROR) {
    fprintf(stderr, "ERROR: Could not parse arguments main\n");
    return 1;
  }
  else if (rv==GWEN_ARGS_RESULT_HELP) {
    GWEN_BUFFER *ubuf;

    ubuf=GWEN_Buffer_new(0, 1024, 0, 1);
    GWEN_Buffer_AppendArgs(ubuf,
                           I18N("This is version %s.\nUsage: %s [GLOBAL OPTIONS] COMMAND [LOCAL OPTIONS]\n\nGlobal Options:\n"),
                           AQHOME_VERSION_STRING,
                           argv[0]);
    if (GWEN_Args_Usage(args, ubuf, GWEN_ArgsOutType_Txt)) {
      fprintf(stderr, "ERROR: Could not create help string\n");
      return 1;
    }
    GWEN_Buffer_AppendString(ubuf, "\n");

    fprintf(stdout, "%s\n", GWEN_Buffer_GetStart(ubuf));
    GWEN_Buffer_free(ubuf);

    fprintf(stderr, "%s\n", I18N("\nCommands:\n\n"));
    GWEN_Funcs_Usage_With_Help(cmdDefArray);

    return 0;
  }
  if (rv) {
    argc-=rv-1;
    argv+=rv-1;
  }

  s=GWEN_DB_GetCharValue(dbArgs, "loglevel", 0, NULL);
  if (s && *s) {
    GWEN_LOGGER_LEVEL ll;

    ll=GWEN_Logger_Name2Level(s);
    GWEN_Logger_SetLevel(NULL, ll);
  }

  AQH_MergeConfigFileIntoConfig(dbArgs, "ConfigFile");

  s=GWEN_DB_GetCharValue(dbArgs, "charset", 0, NULL);
  if (s && *s)
    GWEN_Gui_SetCharSet(gui, s);

  cmd=GWEN_DB_GetCharValue(dbArgs, "params", 0, 0);
  if (!cmd) {
    fprintf(stderr, "ERROR: Command needed.\n");
    return 1;
  }

  func=GWEN_Funcs_Find(cmdDefArray, cmd);
  if (func!=NULL) {
    rv=GWEN_Funcs_Call_DB_NODE_Args(func, dbArgs, argc, argv);
  }
  else {
    fprintf(stderr, "ERROR: Unknown command \"%s\".\n", cmd);
    rv=1;
  }

  GWEN_DB_Group_free(dbArgs);

  AQH_Fini();

  GWEN_Gui_SetGui(NULL);
  GWEN_Gui_free(gui);

  GWEN_Fini();

  return rv;
}





