/*
 *  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/>.
 */

#ifndef __ROLLER_H
#define __ROLLER_H

#include "parameters.h"

static enum Direction direction = RANDOM;

static double roll_theta = 0.0, roll_freq = 0.03;
static double speed = 0;
static int random_speed = 1;

#define BPP_RANDOM_SPEED "random_speed"


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

  plugin_parameters_add_string_list(params, BPP_DIRECTION, DIRECTION_NB, direction_list, direction, DIRECTION_NB-1, "Direction");
  plugin_parameters_add_boolean(params, BPP_RANDOM_SPEED, random_speed, "Random speed");
  if (!random_speed || fetch_all) {
    plugin_parameters_add_double(params, BPP_SPEED, speed, 0.01, 0.4, 0.01, "Rolling speed");
  }

  return params;
}


void
set_speed_parameters(const Context_t *ctx, const json_t *in_parameters, int *speed_changed, int *random_speed_changed)
{
  *speed_changed = plugin_parameter_parse_double_range(in_parameters, BPP_SPEED, &speed) & PLUGIN_PARAMETER_CHANGED;
  *random_speed_changed = plugin_parameter_parse_boolean(in_parameters, BPP_RANDOM_SPEED, &random_speed) & PLUGIN_PARAMETER_CHANGED;
}


void set_parameters(const Context_t *ctx, const json_t *in_parameters);


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);
}


static void
inc_theta(void)
{
  roll_theta += roll_freq;

  if (roll_theta > (2 * M_PI)) {
    roll_theta -= 2 * M_PI;
  } else if (roll_theta < (-2 * M_PI)) {
    roll_theta += 2 * M_PI;
  }
}


static double
get_random_speed(void)
{
  return b_rand_double_range(0.02, 0.1);
}


void
on_switch_on(Context_t *ctx)
{
  random_speed = 1;
  speed = roll_freq = get_random_speed();
  direction = RANDOM;
  if (b_rand_boolean()) {
    roll_freq = -roll_freq;
  }
#ifdef DEBUG
  VERBOSE(printf("[i] %s:%s direction= %s, speed= %f, roll_freq= %f\n", __FILE__, __func__, direction_list[direction], speed, roll_freq));
#endif
}


#endif /* __ROLLER_H */
