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


uint32_t version = 0;
uint32_t options = BO_LENS | BO_NOT_LENS | BO_DISPLACE;
char desc[] = "Mosaic effect";
char dname[] = "Mosaic";

enum Modes { EXPAND=1, SHRINK=-1 }; /* initialization values may be useless */
static enum Modes mode = EXPAND;

#define MAX_SIZE 16
static short max_size = -1;
static short size = 0;


void
on_switch_on(Context_t *ctx)
{
  mode = EXPAND;
  size = 2;
}


static int
gcd(int a, int b)
{
  return b ? gcd(b, a % b) : a;
}


static int
ok(Context_t *ctx)
{
  int p = gcd(WIDTH, HEIGHT);

  /* blah blah checker des trucs ici */
  max_size = ((WIDTH % p) || (HEIGHT % p)) ? p * 2 : p;
  max_size = MIN(max_size, MAX_SIZE);

  if ((p == WIDTH) || (p == HEIGHT) || (p == 1)) {
    return 0;
  }

#ifdef DEBUG
  VERBOSE(printf("[i] mosaic: max_size= %d\n", max_size));
#endif

  return 1;
}


int8_t
create(Context_t *ctx)
{
  if (ok(ctx)) {
    on_switch_on(ctx);
    return 1;
  } else {
    VERBOSE(printf("[!] mosaic: non-standard screen size, disabling plugin.\n"));
    return 0;
  }
}


static void
mosaic(Context_t *ctx)
{
  int i, j;
  const Buffer8_t *src = active_buffer(ctx);
  Buffer8_t *dst = passive_buffer(ctx);

  for (i = 0; i < WIDTH - size; i += size)
    for (j = 0; j < HEIGHT - size; j += size) {
      Pixel_t color = get_pixel_nc(src, i, j);
      /*printf("[d] mosaic: size=%d coords= %d %d %d %d\n", size, i, j, i + size - 1, j + size - 1);*/
      draw_filled_box_nc(dst, i, j, i + size, j + size, color);
      /* draw_filled_box(dst, i, j, i + size - 1, j + size - 1, color); */
    }
}


static void
expand(void)
{
  if (size > max_size) {
    mode = SHRINK;
  } else {
    size += 2;
  }
}


static void
shrink(void)
{
  if (size == 2) {
    mode = EXPAND;
  } else {
    size -= 2;
  }
}


void
run(Context_t *ctx)
{
  mosaic(ctx);

  if (mode == EXPAND) {
    expand();
  } else if (mode == SHRINK) {
    shrink();
  }
}
