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


json_t *
Bank_command(Context_t *ctx, const json_t *arg)
{
  json_t *j_command = json_object_get(arg, "command");
  json_t *j_bank_no = json_object_get(arg, "bank");

  if (!json_is_string(j_command) || !json_is_integer(j_bank_no)) {
    return NULL;
  }

  uint8_t bank_no = json_integer_value(j_bank_no);

  // number sent by the UI is slot + 1
  if ((bank_no < 1) || (bank_no > MAX_BANKS)) {
    return NULL;
  } else {
    --bank_no;
  }

  const char *command = json_string_value(j_command);

  if (is_equal(command, "clear") || is_equal(command, "store") || is_equal(command, "use")) {
#ifdef DEBUG_COMMANDS
    printf(">>> UI_CMD_BANK command= %s bank= %d\n", command, bank_no);
#endif
    json_t *res = json_pack("{ss si}", "command", command, "bank", bank_no + 1);

    if (is_equal(command, "clear")) {
      Context_clear_bank(ctx, bank_no);
      Context_save_banks(ctx);
    } else if (is_equal(command, "store")) {
      if (NULL == ctx->sm->cur->name) {
        Sequence_save(ctx, 0, FALSE, ctx->sm->cur->auto_colormaps, ctx->sm->cur->auto_images);
      }
      Context_store_bank(ctx, bank_no);
      Context_save_banks(ctx);
      json_object_set_new(res, "name", json_string(ctx->sm->cur->name));
    } else {
      // "use" command
      Context_use_bank(ctx, bank_no);
    }

    return res;
  } else {
    return NULL;
  }
}
