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


uint32_t version = 0;
uint32_t options = BO_GFX | BO_SFX | BO_IMAGE;
enum LayerMode mode = LM_OVERLAY;
char desc[] = "Pulse pictures";
char dname[] = "Images pulse";

/* TODO use a Shuffler to take random images */

static const Image8_t *pic = 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);
}


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

  pic = Images_random();
}


void
run(Context_t *ctx)
{
  const Buffer8_t *img;
  Buffer8_t *dst = passive_buffer(ctx);
  float volume;
  uint32_t p, k;

  img = pic->buff;
  volume = Input_get_volume(ctx->input) * volume_scale;
  //volume = expf(volume)/expf(1.0);
  // printf("Vol= %f\n", volume);
  p = (uint32_t)(volume * BUFFSIZE  * 1);

  if (p > 100000) {
    pic = Images_random();
  }

#if 1
  for (k = 0; k < BUFFSIZE; k++) {
    uint32_t rnd = b_rand_uint32_range(0, BUFFSIZE);
    //    printf("%i ", rnd);
    if (rnd <= p) {
      dst->buffer[k] = img->buffer[k];  /* TODO from image */
    } else {
      dst->buffer[k] = 0;  //src->buffer[k];
    }
  }
#else
  for (k = 0; k < BUFFSIZE; k++) {
    dst->buffer[k] = img->buffer[k]*volume; /* TODO from image */
  }
#endif
}
