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


uint32_t version = 0;
uint32_t options = BO_DISPLACE;
char desc[] = "Melt effect";
char dname[] = "Melt";

static int speed = 0;
static double color_factor = 0;


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

  plugin_parameters_add_int(params, BPP_SPEED, speed, -7, 7, 1, "Speed");
  plugin_parameters_add_double(params, BPP_COLOR_FACTOR, color_factor, 0, 1, 0.01, "Color factor");

  return params;
}


void
set_parameters(const Context_t *ctx, const json_t *in_parameters)
{
  plugin_parameter_parse_int_range(in_parameters, BPP_SPEED, &speed);
  plugin_parameter_parse_double_range(in_parameters, BPP_COLOR_FACTOR, &color_factor);
}


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 */
  speed = 3;
  color_factor = 0.5;
}


void
run(Context_t *ctx)
{
  const Buffer8_t *src = active_buffer(ctx);
  Buffer8_t *dst = passive_buffer(ctx);

  int x, y;

  if (speed < 0) {
    for (x = 0; x < WIDTH; x++) {
      set_pixel_nc(dst, x, HEIGHT-1, get_pixel_nc(src, x, HEIGHT-1));
    }

    for (y = HEIGHT-2; y > 0; y--) {
      for (x = 0; x < WIDTH; x++) {
        Pixel_t c = get_pixel_nc(src, x, y);
        int y2 = y + (c >> (8+speed));

        if (y2 > HEIGHT-1) {
          y2 = HEIGHT-1;
        }

        set_pixel_nc(dst, x, y, c * color_factor);
        set_pixel_nc(dst, x, y2, c);
      }
    }
  } else {
    for (x = 0; x < WIDTH; x++) {
      set_pixel_nc(dst, x, 0, get_pixel_nc(src, x, 0));
    }

    for (y = 1; y < HEIGHT; y++) {
      for (x = 0; x < WIDTH; x++) {
        Pixel_t c = get_pixel_nc(src, x, y);
        int y2 = y - (c >> (8-speed));

        if (y2 < 0) {
          y2 = 0;
        }

        set_pixel_nc(dst, x, y, c * color_factor);
        set_pixel_nc(dst, x, y2, c);
      }
    }
  }

  h_line_nc(dst, MAXY, 0, MAXX, 0);
}
