/*
 *  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>
#include <stb_image.h>

static lc_bmp * lc_create_3ch_bmp(int w, int h) {
  lc_bmp *bmp = malloc(sizeof(*bmp));

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

  bmp->buffer = calloc(1, 3 * (w * h));

  if (!bmp->buffer) {
    errno = ENOMEM;
    free(bmp);
    return NULL;
  }

  bmp->type = LC_TYPE_BMP;
  bmp->w = w;
  bmp->h = h;
  bmp->ch = 3;

  return bmp;
}

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++) {
      const uint32_t it = (3 * (y * bg->w + x));
      const stbi_uc *pixel = bg->buffer + it;
      *(bmp->buffer + (3 * (y * bmp->w + x)))     = pixel[0];
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 1) = pixel[1];
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 2) = pixel[2];
    }
  }

  for (int y = 0; y < bmp->h; y++) {
    for (int x = 0; x < bmp->w; x++) {
      if (x < src->w && y < src->h && *(src->buffer + (3 * (y * src->w + x))) != 0) {
        int ym = y + yo;
        int xm = x + xo;
        *(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;
}

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 (*(src->buffer + (y * bmp->w + x)) == 0) {
        continue;
      }

      const uint32_t it = (3 * (y * pattern->w + x));
      const stbi_uc *pixel = pattern->buffer + it;

      *(bmp->buffer + (3 * (y * bmp->w + x)))     = pixel[0];
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 1) = pixel[1];
      *(bmp->buffer + (3 * (y * bmp->w + x)) + 2) = pixel[2];
    }
  }

  return bmp;
}

