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

uint32_t version = 0;
uint32_t options = BO_DISPLACE | BO_SFX;
char dname[] = "Speaker";
char desc[] = "Infinity effect which reacts to volume";


#define NB_FCT 10

static VectorField_t *vf = NULL;

static double volume_scale = 1;


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

  plugin_parameters_add_double(params, BPP_VOLUME_SCALE, volume_scale, 0.1, 10, 0.1, "Volume scale");

  return params;
}


void
set_parameters(const Context_t *ctx, const json_t *in_parameters)
{
  plugin_parameter_parse_double_range(in_parameters, BPP_VOLUME_SCALE, &volume_scale);
}


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 t_complex
fct(t_complex a, guint32 n, gint32 p1, gint32 p2)
{
  t_complex b;
  float fact;
  float an;
  float circle_size;
  float speed;
  float co, si;
  float nn = (float)n/9.0;

  a.x -= HWIDTH;
  a.y -= HHEIGHT;

  an = 0.015*(p1-2*nn)+0.002;
  co = cosf(an);
  si = sinf(an);

  circle_size = HEIGHT*nn*2;
  speed = (float)4000-p2*1000;

  b.x = (co*a.x-si*a.y);
  b.y = (si*a.x+co*a.y);

  fact = (sqrtf(b.x*b.x+b.y*b.y)-circle_size)/speed+1;
  b.x *= fact;
  b.y *= fact;

  b.x += HWIDTH;
  b.y += HHEIGHT;

  /* because infinity access pixels at (b.x + 1, b.y + 1) */
  b.x = MIN( MAX(b.x, 0), MAXX-1);
  b.y = MIN( MAX(b.y, 0), MAXY-1);

  return b;
}


void
on_switch_on(Context_t *ctx)
{
  /* Initialize parameters */
  volume_scale = 1;
}


int8_t
create(Context_t *ctx)
{
  vf = VectorField_new(NB_FCT, &fct);

  return 1;
}


void
destroy(Context_t *ctx)
{
  if (NULL != vf) {
    VectorField_delete(vf);
  }
}


void
run(Context_t *ctx)
{
  /* volume must be between 0 and NB_FCT-1 */
  uint8_t volume = volume = (uint8_t)(Input_get_volume(ctx->input) * volume_scale * NB_FCT);

  if (volume >= NB_FCT) {
    volume = NB_FCT-1;
  }

  VectorField_run(vf, ctx, volume);
}
