/*
 *  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_delete_sequences(Context_t *ctx, const json_t *array)
{
  json_t *deleted = json_array();
  size_t index;
  json_t *value;

  json_array_foreach(array, index, value) {
    if (json_is_string(value)) {
      const char *sequence = json_string_value(value);

      // Try to delete from disk
      if (safe_filename(sequence)) {
        gchar *filename = g_strdup_printf("%s/" SEQUENCES_DIR "/%s.json", g_get_home_dir(), sequence);

        if (g_file_test(filename, G_FILE_TEST_EXISTS)) {
          int ret;
#if GLIB_CHECK_VERSION(2, 6, 0)
          ret = g_unlink(filename);
#else
          ret = unlink(filename);
#endif
          if (!ret) {
            printf("[i] Deleted sequence %s from disk\n", sequence);

            // Now delete from memory
            json_array_append_new(deleted, json_string(sequence));
            Sequences_remove_sequence_by_name(sequence);
          } else {
            fprintf(stderr, "[!] Could not delete sequence %s from disk\n", sequence);
          }
        }
        g_free(filename);
      }
    }
  }

  return json_pack("{so si}", "deleted", deleted, "sequences", sequences->size);
}
