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


static enum PluginOptions
parse_body(json_t *body)
{
  enum PluginOptions opt = BO_NONE;
  const char *key;
  json_t *value;

  json_object_foreach(body, key, value) {
    if (json_boolean_value(value)) {
      opt |= Schemes_str2option(key);
    }
  }

  return opt;
}


// Returns an array of plugins matching options (or all if no POST body)
// POST body contains an object of desired options
int
callback_post_plugins(const struct _u_request *request, struct _u_response *response, void *user_data)
{
  if ((NULL == plugins) || (NULL == plugins->plugins)) {
    return U_CALLBACK_ERROR;
  }

  json_t *body = ulfius_get_json_body_request(request, NULL);
  if ((NULL != body) && !json_object_size(body)) {
    json_decref(body);
    return U_CALLBACK_ERROR;
  }

  const uint8_t filter = (NULL != body);
  enum PluginOptions opt = BO_NONE;

  if (filter) {
    opt = parse_body(body);
  }

  json_t *res = json_array();
  json_t *plugins = Plugins_get();
  size_t index;
  json_t *plugin;

  json_array_foreach(plugins, index, plugin) {
    if (!filter || ((opt & json_integer_value(json_object_get(plugin, "options"))) == opt)) {
      json_t *name_j = json_object_get(plugin, "name");
      const char *name = json_string_value(name_j);
      json_array_append_new(res, json_pack("{sssssb}",
                                           "name", name,
                                           "displayName", json_string_value(json_object_get(plugin, "displayName")),
                                           "favorite", Settings_is_favorite(name)));
    }
  }
  ulfius_set_json_body_response(response, 200, res);
  json_decref(body);
  json_decref(res);

  return U_CALLBACK_COMPLETE;
}


