/*
 *  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 <glib/gstdio.h>
#include "vui.h"
#include "sequences.h"
#include "globals.h"


json_t *
vui_rename_sequence(Context_t *ctx, const json_t *arg)
{
  json_t *res = NULL;

  const json_t *id_j = json_object_get(arg, "id");
  const json_t *index_j = json_object_get(arg, "index");
  const json_t *old_name_j = json_object_get(arg, "oldName");
  const json_t *new_name_j = json_object_get(arg, "newName");

  if (json_is_integer(id_j) && json_is_integer(index_j) && json_is_string(old_name_j) && json_is_string(new_name_j)) {
    const uint64_t id = json_integer_value(id_j);
    const uint64_t index = json_integer_value(index_j);
    const char *old_name = json_string_value(old_name_j);
    const char *new_name = json_string_value(new_name_j);

    if (safe_filename(old_name) && safe_filename(new_name)) {
#ifdef DEBUG_COMMANDS
      printf(">>> VUI_RENAME_SEQUENCE: id=%"PRIu64" index=%"PRIu64" old_name: '%s', new_name: '%s'\n", id, index, old_name, new_name);
#endif
      GList *item = Sequences_find(id);

      if (NULL != item) {
        Sequence_t *seq = (Sequence_t *)item->data;
        gchar *old_file = g_strdup_printf("%s/%s.json", Sequences_get_dir(), old_name);
        gchar *new_file = g_strdup_printf("%s/%s.json", Sequences_get_dir(), new_name);
        GStatBuf sbuf;

        if (!g_lstat(new_file, &sbuf)) {
          res = json_pack("{ss sI ss}", "error", "destination file exists", "index", index, "oldName", old_name);
        } else if (rename(old_file, new_file) != 0) {
          res = json_pack("{ss sI ss}", "error", strerror(errno), "index", index, "oldName", old_name);
        } else {
          xfree(seq->name);
          seq->name = strdup(new_name);
          res = json_pack("{sI ss}",
                          "index", index,
                          "newName", new_name);
        }
        g_free(old_file);
        g_free(new_file);
      }
    }
  }

  return res;
}
