/*
 *  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"
#include "context.h"


int
callback_post_command(const struct _u_request *request, struct _u_response *response, void *user_data)
{
  Context_t *ctx = (Context_t *)user_data;
  const char *cmd = u_map_get(request->map_url, "cmd");

  if (NULL != cmd) {
    const int command = str2command(cmd);

    if (command != -1) {
      if (is_allowed(command)) {
        json_t *res = NULL;

        if (!SequenceManager_lock(ctx->sm)) {
          res = Context_process_command(ctx, (const enum Command)command);
          SequenceManager_unlock(ctx->sm);
        }
        if (NULL == res) {
          json_t *json = json_pack("{ssss}", "command", cmd, "result", "ok");
          ulfius_add_header_to_response(response, "Content-type", "application/json");
          ulfius_set_json_body_response(response, 200, json);
          json_decref(json);
        } else {
#ifdef DEBUG_BULFIUS_POST
          printf("=== callback_post_command: res= %p\n", res);
          char *str = json_dump(res, 0);
          printf("=== %s\n", str);
          xfree(str);
#endif
          ulfius_set_json_body_response(response, 200, res);
          json_decref(res);
        }
      } else {
        ulfius_set_string_body_response(response, 400, "Command not allowed");
      }
    } else {
      ulfius_set_string_body_response(response, 400, "Command not found");
    }
  } else {
    ulfius_set_string_body_response(response, 400, "No command");
  }

  return U_CALLBACK_COMPLETE;
}
