/*
 *  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 "translation.h"
#include "parameters.h"

/* we don't use Randomness in our version --oliv3 */

uint32_t version = 0;
uint32_t options = BO_DISPLACE;
char dname[] = "Space in";
char desc[] = "Inwards space move";


static Translation_t *t_space = NULL;

#define DEFAULT_SPEED 100
/* #define DEFAULT_RAND   70 */

/* int Randomness = DEFAULT_RAND; */
static int speed = DEFAULT_SPEED;
static double speed_factor = 0;


json_t *
get_parameters(const uint8_t fetch_all)
{
  json_t *params = json_object();

  plugin_parameters_add_double(params, BPP_SPEED_FACTOR, speed_factor, 0, 10, 0.01, "Speed factor");

  return params;
}


static Map_t
cth_space(const short in_x, const short in_y)
{
  const uint16_t x = in_x, y = in_y;
  int dx, dy, map_x, map_y;
  Map_t m;

  dx = x - CENTERX;
  dy = y - CENTERY;

  map_x = (int)((float)(x) - (float)(dx * speed) / 700.0);
  map_y = (int)((float)(y) - (float)(dy * speed) / 700.0);

  if ((map_y > MAXY) || (map_y < MINY) || (map_x > MAXX) || (map_x < MINX)) {
    map_x = 0;
    map_y = 0;
  }

  m.map_x = map_x % WIDTH;
  m.map_y = map_y % HEIGHT;

  return m;
}


static void
init_params(void)
{
  speed = speed_factor * b_rand_uint32_range(30, 100);
  /* Randomness = b_rand_uint32_range(12, 100); */
}


void
set_parameters(const Context_t *ctx, const json_t *in_parameters)
{
  int reload = 0;
  reload |= plugin_parameter_parse_double_range(in_parameters, BPP_SPEED_FACTOR, &speed_factor);

  if (reload) {
    Translation_delete(t_space);
    t_space = Translation_new(&cth_space, &init_params);
  }
}


json_t *
parameters(const Context_t *ctx, const json_t *in_parameters, const uint8_t fetch_all)
{
  if (NULL != in_parameters) {
    set_parameters(ctx, in_parameters);
  }

  return get_parameters(fetch_all);
}


void
on_switch_on(Context_t *ctx)
{
  speed_factor = 1;
  Translation_batch_init(t_space);
}


int8_t
create(Context_t *ctx)
{
  t_space = Translation_new(&cth_space, &init_params);

  return 1;
}


void
destroy(Context_t *ctx)
{
  Translation_delete(t_space);
}


void
run(Context_t *ctx)
{
  Translation_run(t_space, ctx);
}
