/*
 *  This program 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.
 *
 *  This program 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.
 *  Author: g0tsu
 *  Email:  g0tsu at dnmx.0rg
 */

#include <libcaptcha.h>
#include <global.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

void lc_recalculate_arr(lc_arrGlyph *arr) {
  int xline = 0,
      yline = 0;

  for (int i = 0; i < arr->size; i++) {
    yline = MAX(arr->items[i]->h + arr->items[i]->y, yline);
    xline = arr->items[i]->w + arr->items[i]->x;
  }

  arr->w = xline;
  arr->h = yline;
}

void lc_randomize_arr_rotation_180(lc_arrGlyph *arr) {
  int arrsiz = arr->size;
  uint8_t bytes[arrsiz];
  lc_bmp *bmp;

  lc_random_bytes(&bytes, arrsiz);

  for (int i = 0; i < arrsiz; i++) {
    if (bytes[i] > 100) {
      bmp = lc_rotate_bmp_180(arr->items[i]->buffer, arr->items[i]->w, arr->items[i]->h);
      memcpy(arr->items[i]->buffer, bmp->buffer, (bmp->w * bmp->h) * bmp->ch);
      lc_free(bmp);
    }
  }
}

void lc_randomize_arr_x(lc_arrGlyph *arr, int delta) {
  int arrsiz = arr->size;
  int xline = 0;
  uint8_t bytes[arrsiz];

  lc_random_bytes(&bytes, arrsiz);

  for (int i = 0, j = 0 ; i < arrsiz; i++) {
    int r = bytes[j++] % delta;
    arr->items[i]->x += r;

    for (int j = i + 1; j < arrsiz; j++) {
      arr->items[j]->x += r;
    }

    xline = MAX(arr->items[i]->x + arr->items[i]->w, xline);
  }

  arr->w = xline;
}

void lc_randomize_arr_y(lc_arrGlyph *arr, int delta) {
  int arrsiz = arr->size;
  int dhalf = delta / 2;
  uint8_t bytes[arrsiz];

  lc_random_bytes(&bytes, arrsiz);

  for (int i = 0, j = 0 ; i < arrsiz; i++) {
    int r = bytes[j++] % delta;
    arr->items[i]->y += r;
  }

  lc_recalculate_arr(arr);
}

