/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "bulfius.h"


void
Context_process_commands(Context_t *ctx)
{
  assert(NULL != ctx->commands);
  gpointer *ptr = g_async_queue_try_pop(ctx->commands);

  while (NULL != ptr) {
    Command_t *cmd = (Command_t *)ptr;
    const char *command = command2str(cmd->cmd);
#ifdef DEBUG_COMMANDS_QUEUE
    xdebug("%s: cmd= %p, cmd->type= %d, cmd->cmd= %d (%s)\n", __func__, cmd, cmd->type, cmd->cmd, command);
#endif
    json_t *res = NULL;
    switch (cmd->type) {
    case CT_SDL2:
      res = Context_process_command(ctx, cmd->cmd);
#ifdef DEBUG_COMMANDS_QUEUE
      DEBUG_JSON("res", res, 1);
#endif
      bulfius_send_command_result(ctx, "command", command, NULL, res, cmd->emitter);
      break;

    case CT_WEB_UI:
      res = Context_process_ui_command(ctx, cmd->cmd, cmd->arg);
#ifdef DEBUG_COMMANDS_QUEUE
      DEBUG_JSON("arg", cmd->arg, 1);
      DEBUG_JSON("res", res, 1);
#endif
      bulfius_send_command_result(ctx, "uiCommand", command, cmd->arg, res, cmd->emitter);
      break;

    case CT_VUI:
      res = Context_process_vui_command(ctx, cmd->cmd, cmd->arg);
#ifdef DEBUG_COMMANDS_QUEUE
      DEBUG_JSON("arg", cmd->arg, 1);
      DEBUG_JSON("res", res, 1);
#endif
      bulfius_send_command_result(ctx, "vuiCommand", command, cmd->arg, res, cmd->emitter);
      break;
    }
    Command_delete(cmd);
    ptr = g_async_queue_try_pop(ctx->commands);
  }
}
