/*
 *  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 "globals.h"
#include "sequence.h"
#include "images.h"
#include "colormaps.h"

#define SEQUENCE_VERSION 4


json_t *
Sequence_to_json(const struct Context_s *ctx, const Sequence_t *s, const uint8_t full, const uint8_t parameter_value_only, const char *sequence_name)
{
  json_t *plugins_j = json_array();
  json_t *sequence_j = json_pack("{si sI ss*}", "version", SEQUENCE_VERSION, "id", s->id, "name", sequence_name);

  if (full) {
    json_object_set_new(sequence_j, "autoColormaps", json_boolean(s->auto_colormaps));
    json_object_set_new(sequence_j, "colormap", json_string(Colormaps_name(s->cmap_id)));
    json_object_set_new(sequence_j, "autoImages", json_boolean(s->auto_images));
    json_object_set_new(sequence_j, "image", json_string(Images_name(s->image_id)));
  }

  /* iterate over plugins list */
  for (GList *layers = g_list_first(s->layers); NULL != layers; layers = g_list_next(layers)) {
    Layer_t *layer = (Layer_t *)layers->data;
    Plugin_t *p = layer->plugin;
    json_t *j_plugin = json_pack("{sb ss ss si ss}",
                                 "lens", (NULL != s->lens) && (p == s->lens),
                                 "name", p->name,
                                 "displayName", p->dname,
                                 "version", p->version,
                                 "mode", LayerMode_to_string(layer->mode));

    if (NULL != p->parameters) {
      json_t *j_params = p->parameters(NULL, NULL, 0);

      if (parameter_value_only) {
        json_object_set_new(j_plugin, "parameters", plugin_parameters_to_saved_parameters(j_params));
        json_decref(j_params);
      } else {
        json_object_set_new(j_plugin, "parameters", j_params);
      }
    }
    json_array_append_new(plugins_j, j_plugin);
  }
  json_object_set_new(sequence_j, "plugins", plugins_j);
  json_object_set(sequence_j, "params3d", s->params3d);
  json_object_set_new(sequence_j, "bandpassMin", json_integer(s->bandpass_min));
  json_object_set_new(sequence_j, "bandpassMax", json_integer(s->bandpass_max));

  return sequence_j;
}
