#include <stdio.h>
#include <libcaptcha.h>

lc_bmp *load_pattern(char *filename, int x, int y, int w, int h) {
  lc_bmp *img = lc_load_png(filename);
  lc_bmp *cropped;

  if (!img) {
    perror("lc_load_png()");
    return NULL;
  }

  cropped = lc_crop_bmp(img, x, y, w, h);

  if (!cropped) {
    perror("lc_crop_bmp()");
    return NULL;
  }

  lc_free(img);

  return cropped;
}

int main() {
  char * str = "CRAZYSTUFF";
  char * fontfile = "../ttf/dejavu.ttf";

  lc_fontBuffer *font = lc_create_font(fontfile);
  lc_arrGlyph *tmp;
  lc_arrGlyph *arr;
  lc_bmp * text;
  lc_bmp * pattern;
  lc_bmp * bg;
  lc_bmp * bmp;
  lc_bmp * captcha;

  if (!font) {
    perror("lc_create_font()");
    return 1;
  }

  tmp = lc_str_to_arr(font, str, 50, 70);

  if (!tmp) {
    perror("lc_str_to_arr()");
    return 1;
  }

  arr = lc_randomize_arr_rotation(tmp, 180);

  if (!arr) {
    perror("lc_randomize_arr_rotation()");
    return 1;
  }

  lc_randomize_arr_x(arr, 10);
  lc_randomize_arr_y(arr, 10);

  text = lc_create_image(arr);

  if (!text) {
    perror("lc_create_image()");
    return 1;
  }

  pattern = load_pattern("../patterns/96b.png", 100, 200, text->w, text->h);

  if (!pattern) {
    return 1;
  }

  bg = load_pattern("../patterns/96c.png", 300, 20, pattern->w + 20, pattern->h + 20);

  if (!bg) {
    return 1;
  }

  bmp = lc_pattern_apply(pattern, text);

  if (!bmp) {
    perror("lc_pattern_apply()");
    return 1;
  }

  captcha = lc_pattern_merge(bg, bmp, 10, 10);

  if (!captcha) {
    perror("lc_pattern_merge()");
    return 1;
  }

  lc_save_png("./example6.png", captcha);

  lc_free(tmp);
  lc_free(captcha);
  lc_free(bg);
  lc_free(text);
  lc_free(pattern);
  lc_free(arr);
  lc_free(bmp);
  lc_free(font);
  return 0;
}
