/*
 *  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 <stdio.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>

/*
 * Merges two 24-bit bitmaps using x,y offset
 */
lc_bmp * lc_pattern_merge(lc_bmp *bg, lc_bmp *src, int xo, int yo) {
  lc_bmp *bmp = lc_create_3ch_bmp(bg->w, bg->h);

  if (!bmp) {
    errno = ENOMEM;
    return NULL;
  }

  for (int y = 0; y < bmp->h; y++) {
    for (int x = 0; x < bmp->w; x++) {
      *(bmp->buffer + (3 * (y * bmp->w + x)))     = *(bg->buffer + (3 * (y * bg->w + x)));
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 1)     = *(bg->buffer + (3 * (y * bg->w + x)) + 1);
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 2)     = *(bg->buffer + (3 * (y * bg->w + x)) + 2);
    }
  }

  for (int y = 0; y < bmp->h; y++) {
    for (int x = 0; x < bmp->w; x++) {
      int ym = y + yo;
      int xm = x + xo;

      if (xm < bmp->w && ym < bmp->h && x < src->w &&
          y < src->h && *(src->buffer + (3 * (y * src->w + x))) != 0) {
        *(bmp->buffer + (3 * (ym * bmp->w + xm))) = *(src->buffer + (3 * (y * src->w + x)));
        *(bmp->buffer + (3 * (ym * bmp->w + xm)) + 1) = *(src->buffer + (3 * (y * src->w + x) + 1));
        *(bmp->buffer + (3 * (ym * bmp->w + xm)) + 2) = *(src->buffer + (3 * (y * src->w + x) + 2));
      }
    }
  }
  return bmp;
}

/*
 * Applies 24-bit pattern to 8-bit bitmap
 */
lc_bmp * lc_pattern_apply(lc_bmp *pattern, lc_bmp *src) {
  lc_bmp *bmp = lc_create_3ch_bmp(src->w, src->h);

  if (!bmp) {
    errno = ENOMEM;
    return NULL;
  }

  for (int y = 0; y < bmp->h; y++) {
    for (int x = 0; x < bmp->w; x++) {
      if (y > pattern->h || x > pattern->w || *(src->buffer + (y * bmp->w + x)) == 0) {
        continue;
      }

      *(bmp->buffer + (3 * (y * bmp->w + x)))     = *(pattern->buffer + (3 * (y * pattern->w + x)));
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 1) = *(pattern->buffer + (3 * (y * pattern->w + x)) + 1);
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 2) = *(pattern->buffer + (3 * (y * pattern->w + x)) + 2);
    }
  }

  return bmp;
}

